Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
8 views

Module 1

Introduction to C

Uploaded by

ushashank720
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Module 1

Introduction to C

Uploaded by

ushashank720
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 151

Principles of Programming in C

Unit 1 : Introduction to C
Syllabus Unit 1
Introduction to C
• Basic Organization of a Computer, Types of Programming Languages,
Program Design Tools, Introduction to C, Structure of C program,
Writing the first C Program, Compiling and Executing C Programs, C
Tokens, Basic Data Types in C, Operators in C, Evaluating
Expressions, Type Conversion and Typecasting, Example Programs.
Installation of code blocks
https://www.codeblocks.org/downloads/
Basic Organization of a Computer - CLASSIFICATION OF COMPUTERS

Computers can be broadly classified into four categories based on their speed, amount of data that
they can hold, and price.

Classification of Computers

Super Computers Mainframe Computers Mini Computers Micro Computers

Dumb Intelligent
Terminal Terminal

Desktop Laptop Workstation Network Handheld

Smartphones Tablet PCs


Basic Organization of a Computer

A computer is an electronic device which basically performs five major operations which includes:
1) accepts data or instructions (input)
2) stores data
3) process data
4) displays results (output) and
5) controls and co-ordinates all operations inside a computer
• Input: This is the process of entering data and instructions into the computer. Different input
devices such as mouse, keyboard, scanner and trackball can be used to enter the instructions. It is
the responsibility of the input device to convert the input data into binary code.
• Storage: This is the process of saving data and instructions permanently in the computer such that
it can be used for processing. There are 2 types of storage areas

1. Primary storage (Main memory): This area stores data, intermediate results and recently generated results that
are currently being worked on.
➢ The storage area that is directly accessible by the CPU at very high speed.
➢ It is very expensive, limited capacity and volatile.
➢ Eg : Random Access memory

2. Secondary Storage (Auxiliary Memory): this area stores the data that is not accessed frequently (as compared
to the data in primary storage.
➢ It is a non-volatile memory medium that preserves data until and unless it has been deleted or overwritten.
➢ It supplements the limited storage capacity of primary memory
➢ Eg : CD , Hard disk drives, Magnetic disk
Difference between primary and secondary memory

Primary memory Secondary memory

Known as main memory or internal memory Known as auxiliary memory or External memory

Eg : RAM, ROM , Cache, EPROM Eg: HDD , CD, DVD ,Flash drives

Volatile memory : Non volatile memory:


Temporarily stores device while in use Permanently stores data

CPU directly accesses data CPU does not directly accesses data

Power cut causes loss of data Power cut does not cause loss of data

Limited storage capacity Expansive and scalable

Faster data access Slower data access


• Output: Process of giving the results to outside world . Various output devices such as monitor ,
speaker printers are used. It is the responsibility of the output device to convert the binary data to
human understandable form before displaying it to the user.
• Control Unit : This unit manages and controls all components of the computer system. The CU
decides which instruction needs to be executed. The CU activates and monitors operations of other
units.
• Arithmetic Logic Unit (ALU): The entire processing of the instructions is done here.

Processing : The process of performing operations on the data as per instructions specified by the
user is called processing. Data and instructions is taken from the primary memory and transferred to
ALU for calculations. The intermediate results is stored in the main memory. When processing is
complete the final result is transferred to main memory.
Types of Programming Language
A programming Language is a language used by a user to instruct a computer to
perform certain computations.
Each programming language has its own vocabulary of syntax and semantics for
instructing a computer.
Types of programming language : C,C++,COBOL,FOTRAN,Pascal,Python,Java etc
Types of Programming Language
Programming Language can be divided into 3 types :
1. Machine level language - is a language that consists of a set of instructions that
are in the binary form 0 or 1
2. Assembly level language - is a type of low-level programming language which
consists of binary and hexadecimal characters with some English like
commands. Assembly languages are designed to be readable by humans.
3. High level Language - language that is designed to be easily understood by
humans. It uses syntax that is similar to human language to form instructions.
Program Design Tools
• Algorithms
➢ Step by step description on how to arrive at a solution.
➢It provides a blueprint of the solution
➢It should be precise , Unambiguous , Once the algorithm terminates the desired result must
be obtained.

• Flowcharts
➢ Graphical or symbolic representation of a process.
➢Helps user to visualize the logic of the process which helps them to understand the process
better , find flaws , bottlenecks.

• Pseudocodes
➢ Compact and informal high level description of an algorithm
➢Helps user to focus on the logic of the algorithm without worrying about the details of
language syntax.
➢An ideal pseudocode must be complete , descriptive such that it can be translated to a
programming language straightaway.
Algorithm
What is an Algorithm?

◼ Algorithm is a step-by-step procedure, which defines a set of


instructions to be executed in a certain order to get the desired
output.
Write algorithm to Print Hello World

Step 1: Start
Step 2: Print “Hello World”
Step 3: Stop
Write algorithm to calculate the sum
and average of two numbers.
◼ Step1 : Start
◼ Step2: Declare two variables n,m,sum,avg
◼ Step3 : Read two numbers n,m
◼ Step4 : Calculate sum=n+m
◼ Step5 : Calculate avg=sum/2
◼ Step6 : Print sum,avg
◼ Step7 : Stop
Write algorithm to calculate simple interest.
Step 1: Start
Step 2: Read Principal Amount, Rate and Time
Step 3: Calculate Interest using formula SI=
((amount*rate*time)/100)
Step 4: Print Simple Interest
Step 5: Stop
INTRODUCTION TO
FLOWCHARTS
FLOWCHARTS
• The first flowchart was created by Von Neumann in 1945.
• Flowchart are the graphical representation of a solution to a
particular problem, which comes under the category of programming
practices and techniques.
• In simple words flowchart is a graphical representation of a program.
• Flowchart are symbolic diagram which shows type of data(numeric ,
character), data flow, control flow, and programming logics and
alogorithms.
Introduction to C
Characteristics of C
 Robust language which consists of a number of built- in
function & operators which can be used to write complex
programs
 Easy to learn
 Used in development of Software (both application/system)
 C programs are efficient and fast
 Highly portable- works on different OS
 Structured programming
BASIC STRUCTURE / FUNCTIONAL UNITS OF COMPUTER
4 steps of C program

1. Writing and editing a program


2. Compiling the program
3. Linking the program with the required
library modules
4. Executing/ running the programs
Building a C program
WRITING AND EDITING PROGRAMS
 The software used to write programs is known as
a text editor.
 It is used to enter, change and store character
data.
 The completed program is known as a source file
which is input to the complier.
 Eg: Turbo C(TC), Borland C, Microsoft C/C++ ,
ANSI C, GCC,Tiny C compiler , MinGW Compiler
Compiling a C program
The job of the complier is to translate Source file to Machine level language

1. The Preprocessor
❖ Preprocessor reads the source code and prepares it for translator.
❖ The preprocessor scans for preprocessor commands and makes substitution in special
library codes.

2. The Translator
❖ The translates preprocessed code and results a object module is the code in
machine language.
❖ Translator is the one which does the actual conversion of program into machine
language.
LINKING & LOADING PROGRAMS
 The linker assembles input/output processes and
mathematical library functions and the various
files together
 To execute a program, we use an operating
system command such as run, to load the program
into primary memory (loader) and execute it.
Basic Structure of C program
Sample C programs

/* PROGRAM TO PRINT WELCOME */


#include<stdio.h>
void main()
{
printf(“Hello World”);
}
Points to remember
1. C program makes a distinction between UPPERCASE and lowercase letters
hence sum is different from SUM ,Sum
2. Only Single main () is allowed. Multiple main() is not allowed
3. Most of the statements within main and user-defined functions must end with a ‘;’
4. C is a free form language – C compiler does not care where in the line you
start typing . Hence proper indentation must be followed just for ease in
readability
5. Save all the files using a .c extention
Characters in C
Character set (ALPHABET)
 The first step in learning C language is to learn alphabets of C language.
 The set of alphabets in C language is called Character set
 Valid characters of C languages are :
1. Uppercase A…Z
2.Lowercase a…z
3.Digits 0…9
4.Special characters like , . ; : etc
5.White spaces [tab , blank space, carriage return etc]
C tokens (WORDS)
 Token is a smallest or basic unit of C program. One or more characters are
grouped in sequence to form meaningful words. This meaningful word is
called token.
Keywords
 Every Word in C is a keyword or identifier
 Keywords are basic building blocks for program statements
 Keyword have fixed meanings and it cannot be changed.
 Keyword should be written in lowercase.
 Some keywords are given below

auto , double , int, struct , break, else, long , switch, case, char, do , while , if,
goto , const , continue , default , float , for , short , return
Identifiers (Variables)
 Identifiers are user-defined names
 Names of variables, functions and arrays as declared by user
 Rules for identifiers
1. First character must be an alphabet or underscore
2. Remaining characters can be letters, digit or underscore
3. Must not contain white space or any special charcters
4. Keywords cannot be used as identifiers
5. There cannot be two successive underscores
Let’s Test !!!

1…2…3…
Identify valid and invalid Identifiers!!!

Sl example Sl No Example
No
1 a 8 $Sum
2 Student_name 9 _sum
3 Num1 10 Student name
4 Sum-salary 11 char
5 2names 12 int
6 HRA 13 23_student
7 DeptCode 14 @name
Answers!!!

Sl No Example Sl No Example
1 a 8 $Sum
2 Student_name 9 _sum
3 Num1 10 Student name
4 Sum-salary 11 char
5 2names 12 int
6 HRA 13 23_student
7 DeptCode 14 @name
Differences between Keyword and Identifier
Keywords Identifiers

Has predefined meaning in C Does not have predefined meaning


language

These are instruction given to the These are not instruction to compiler
compiler

Example:if, int etc These are names introduced in our


program

Example: sum , length etc


Data Types
 Indicates the type of data the variable can hold.
 Each variable can hold a numeric or non numeric data
 3 classes of data types are available
1. Primary(or built-in) data type : eg int , float etc
2. Derived data type : eg array , functions, structures, pointers etc
3. User defined data type eg : enum , Typedef;
Built-in (Primary )Data Type

PRIMARY DATA TYPE

VOID DOUBLE
INTEGER
PRECISION
FLOATING
CHARACTER FLOATING POINT
POINT
A little bit about ‘BIT’

 8 bits = 1Byte
 int a= 5 ;
1. void data type
 void type has no value
 Keyword : void
 Used mainly to specify the type of function – when a function is declared void
it does not return any value to the calling function
2. Character Type

 Keyword: char
 Defines single character – Uses upto 8 bits(1 byte) of internal storage
 Signed or unsigned qualifier is used to vary the range
 Format specifier ‘ %c ‘
 Range : -128 to 127

unsigned char : 1 Byte : 0 to 255


signed char : 1 Byte : -128 to 127 char s=‘#’;
printf(“%c”,s);
printf(“%i”,s);

0 0 1 0 0 0 1 1

ASCII Value of # is 35
Code to demonstrate unsigned char

#include<stdio.h>
int main()
{

int chr = 201;


unsigned char i = chr;
printf("unsigned char: %c\n", i);

return 0;
}
#include<stdio.h>
void main()
Output : A
{
a
char ch1=‘A’;
65
char ch2=‘a’
97
printf(“%c”,ch1);
printf(“%c”,ch2);
printf(“%i”,ch1);
printf(“%i”,ch2);
}

ASCII Value : A= 65 , B= 66 ,….


a =97 , b=98 …
3. Integer type (int)
➢ Integer type takes 2 bytes of storage space (16 bits)
➢ Keyword : int 0 0 0 0 0 0 0 0
➢ Format Specifier : %d 0 0 0 0 0 1 0 1
➢ The maximum integer value that can be stored in
16 bit machine is : -32768 to +32767
32 bit machine is : -2,147,483,648 to
+2,147,483,647
➢ Out of 16 bits one bit is reserved for sign and remaining 15 bits is reserved for
magnitude of the number
➢ For larger or smaller numbers we use long or short keyword along with signed
or unsigned form.
#include<stdio.h>
void main()
{
int a=5;
printf(“%d”,a);
}
OutPut : 5
4. Floating Point
(float) 5. Double Precision
 Used to store decimal numbers  Used to store decimal number
with 6 digits of precision when higher precision is required
 32 bits (4 bytes) storage space is  Using double gives a precision
reserved upto 16 digits.
 Keyword : float  289.0000000123456671
 Format specifier : %f  64 bits ( 8 bytes) storage space is
reserved
 Keyword : double
 Format specifier : %lf
 long double : upto 80 bits
How is a decimal number stored ??
Consider the instruction float PI=3.14;

S Sign bit : 0
0 0011 . 00100….
E Exponent : 0011
F : Fraction :
Shift the decimal to the right of the MSB ‘1’
0.14 * 2 = 0.28 = 0
0 001. 100100…
0.28 * 2 = 0.56 = 0
Since we made only 1 position shift we need
0.56 * 2 = 1.12 = 1
to add 1 to the bias ie 127. 127 + 1= 128
0.12 * 2 = 0.24 = 0
0.24 * 2 = 0.48 = 0
Therefore the exponent value now is binary
…..
equivalent of 128 : 1000 0000
….. Therefore the Fraction part is 00100

3.14 is stored as 0 1000 0000 100100…..


Strings
 One dimensional array of /*Program to print string hello */
characters terminated by null ‘\0’ #include <stdio.h>
 Strings are written inside a pair of void main ()
quote eg: “computer”
{
 Null is introduced by the compiler
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
itself
printf("Greeting message: %s", greeting );
 Strings in C can be manipulated
with many in-built functions like }
strcpy , strlen etc

Output :
Greeting message : Hello
Fill in the blanks
1. ____ num=9;
2. ____ amt=123.90;
3. _____ code=‘A’;
4. _____ pi=3.141519265367;
5. ______ A= 509875;
6. ______ msg[ ] =“Hi”;
7. ______ int a = 5678945679;
Constants
 Constants are data values that cannot be changed during the execution of a
program.
 C supports following types of constants
• Integer constants
• Character constants
• Boolean constants
• Floating point constant
• String constants
Syntax 1 : #define identifier value
Output
#include<stdio.h> area = 50
#define LENGTH 10
#define WIDTH 5

void main()
{
int area;
area=LENGTH * WIDTH;
printf(“area = %d”, area);
}
Syntax 2 : const type variable = value
Output
#include<stdio.h> area = 50
void main()
{
const int LENGTH = 10;
const int WIDTH = 5;

int area;

area=LENGTH * WIDTH;
printf(“area = %d”, area);

}
Write a c program to find area of circle
/*program to find area of circle */
#include<stdio.h>
#define PI 3.14
void main()
{
int radius ,area;
printf(“enter radius “);
scanf(“%d”,&radius);
area = PI* radius*radius;
printf(“ area = %d”, area);
}
Declaration Of data types
 When we declare a variable it does 2 things
1. Tell compiler what the variable name is
2. It specifies what type of data the variable will hold
Hence declaration of variables must be done before they are used in the program
 Syntax
Data_Type varlist semicolon

 Data_Type : int , char, float,double


 Varlist : variable list where each variable is separated by comma
 Semicolon : ;
 Eg int salary , commission , total_salary ;
float area;
char a;
double ratio;
Assigning Values to variables
 Giving values to the variables learnt so far is called assignment of values or
initialization of variable
 ‘=‘ assignment operator is used for this purpose

Syntax : Variable_name = value;

 Variable_name : name given to memory location where the value will be


stored
 Value : constant or variable
 Assignment of values can happen both in declaration part of main and also in
excutable part of main
Assignment in declaration part Assignment in executable part

#include<stdio.h> #include<stdio.h>
void main() void main()
{ {
int a= 10 , b=5 , sum; int a, b, sum;
sum=a+b; a=10;
printf(“sum= %d”,sum); b=5;
} sum = a+b;
printf(“sum=%d”,sum);
Output: }
sum = 15
Output:
sum=15
Let’s Ponder
int a=b=c=5; radius=5;
_____________________________ 3.14*radius*radius= area;
float x, y, z;
printf(“area=%d”,area);
x=y=z=PI ;
____________________________
______________________________
float fr , centi; 3=b=4=a;
printf(“enter farenheit “);
scanf(“%f”,&fr); ____________________________
cent = 5.0/9.0*(fr-32); count=count+1;
printf(“centigrade = %f”,cent); _____________________________
main()
________________________________
slope= (y2-y1)÷(x2-x1); {
int e,d=50,c=100;
e=c;
c=d;
d=e;
printf(“e=%d,c=%d,d=%d”,e,c,d);
}
________________________
Input and Output Operations
printf()

 printf() is a function used to print data


 Specific format specifier is used depending upon the type of data you want to
print on the screen

Format Data Type


Specifier
%d int
%c char
%f float
%lf double
#include<stdio.h> Output
void main()
{ 5
char d='A'; 6.678
int a= 5; 65.90008
float b=6.678; A
double c=65.90008;
printf("%d \n",a);
printf("%f \n",b);
printf("%lf \n",c);
printf("%c \n",d);
}
scanf()
 Function used to read input from user
 Specific format specifier is used depending upon the type of data you want to
read from the user
#include<stdio.h>
void main()
{
char d;
int a;
float b;
double c;
printf("enter value of d(char) : ");
scanf("%c",&d);
printf("enter value of a (int) : ");
scanf("%d",&a);
printf("enter value of b (float) : ");
scanf("%f",&b);
printf("enter value of c(double) : ");
scanf("%lf",&c);
printf("value of a is %d \n",a);
printf("value of b is %f \n",b);
printf("value of c is %lf \n",c);
printf("value of d is %c \n",d);
Write a C program to read Grade, CGPA,
age and phone number and print the
same on the monitor
#include<stdio.h>
void main()
{ OUTPUT
char gr; enter grade & cgpa :

float cg; enter age and phone num :

int age,num; a 6.7

printf("enter grade & cgpa : \n"); 34


printf("enter age and phone num : \n"); 80787
scanf("%c%f",&gr,&cg);
scanf("%d%d",&age,&num); grade is : a
printf("\n grade is : %c",gr); cgpa is : 6.700000

printf("\n cgpa is : %f",cg); age is : 34

printf("\n age is : %d",age); phone num is : 80787

printf("\n phone num is : %d",num);


}
Write a C program to read a students
name from the user
#include <stdio.h>
void main() OUTPUT
{ Enter name: rama
char name[20]; Your name is rama.
printf("Enter name: ");
scanf("%s",name);
printf("Your name is %s.", name);
}
 Write a program to add two integer numbers and print the same.
 Write a program to add two integer numbers accepted from the user and print the
same.
 Write a C program to print your name , DOB and mobile number [each element in
new line]
 Write C program to accept radius from user and print the area of circle on the
screen [note : radius and area should be decimal value]
 Write a C program to find area of triangle .
 Write a C program to perform basic arithmetic operations such as sum, difference,
product and quotient i)fixed values of operands ii)on user entered value of
operands. Print result of each operation . [Note: in divide assume no 0 is entered
by the user]
 Write a C program that takes hours and minutes as input, and calculates the total
number of minutes
 Write a C program to print the following pattern on the screen using just ‘printf() ‘
*
**
***
****
UNIT 2
Operators & expressions
Operator
 An operator is a symbol that tells the computer to perform certain
mathematical or logical manipulations
 Operators used in programs to evaluate data and variables
 Example : + , - , * , /

Operands
➢ Operand is a variable or constant which returns an value.
➢ Example: a + b
Here ‘a’ and ‘b’ are operands. + is operator.

Expression
 A sequence of operands and operators that reduces to single value is an
expression.
Classification of Operators

1. Based on number of operands:


a) Unary operators: Uses only one operand. Ex: unary minus
(-b), increment operator(a++,++a) , decrement operator(--a, a--)
b) Binary operators: Uses two operands and one operator in between the
operands Ex: a+b , a-b etc
c) Ternary operators Ex: ? and :
d) Special operators Ex: comma(,), sizeof() etc.
Unary Minus

Unary operators: Uses only one operand. Ex: unary plus(+a), unary minus
(-b), increment operator(a++,++a) , decrement operator(--a, a--)
int a=10;
int b=-(a); (i.e b=-10)
Increment & Decrement Operator

 Increment operator increases the  Decrement operator decreases the


value of a variable by 1 value of a variable by 1
 Pre-increment : increases the value  Pre Decrement :decreases the value
before assigning to variable ++i before assigning to variable --i
x = 10;
x = 10;
x= x+1; y =--x; x= x-1;
y =++x;
y=x; y=x;

 Post-Increment :increases the value  Post-Decrement :decreases the value


after assigning to variable i++ after assigning to variable i--
x = 10;
x = 10; y =x--; y=x;
y =x++; y= x; x= x-1;
x=x+1
Remember!!

 While applying Increment / Decrement operator , the operand must


be a variable.
 Increment / Decrement operator cannot be applied to a constant or
an expression.
Program to demonstrate increment & decrement operator
#include<stdio.h> a = 5;
void main() printf("value of a = %d \n", a);
{ b = a--; //POST DECREMENT
int a,b; printf("value of b after a-- = %d \n",b);
a=1; printf("value of a after a-- = %d \n",a);
printf("value of a = %d \n", a);
b=a++; //POST INCREMENT a = 5;
printf("value of b after a++ = %d \n", b); printf("value of a = %d \n", a);
printf("value of a after a++= %d \n", a); b = --a; //PREDECREMENT
printf("value of b after --a = %d \n",b);
a=1; printf("value of a after --a = %d \n",a);
printf("value of a = %d \n", a); }
b=++a; //PRE INCREMENT
printf("value of b after ++a = %d \n",b);
printf("value of a after ++a = %d \n",a);
Output
value of a = 1
value of b after a++ = 1
value of a after a++= 2
value of a = 1
value of b after ++a = 2
value of a after ++a = 2
value of a = 5
value of b after a-- = 5
value of a after a-- = 4
value of a = 5
value of b after --a = 4
value of a after --a = 4
Work the output out!!!
#include<stdio.h>
Output
void main()
++a= 11
{
++b=16
int a=10,b=15,c=20,d=25;
c++=20
printf("++a= %d \n",++a);
d++=25
printf("++b=%d \n",++b);
++a=12
printf("c++=%d \n",c++);
++b=17
printf("d++=%d \n",d++);
c++=21
printf("++a=%d \n",++a);
d++=26
printf("++b=%d \n",++b);
printf("c++=%d \n",c++);
printf("d++=%d \n",d++);
}
Let’s Ponder

int a=2,b=10,c=0,p,q,r;
p= a++ + b-- + ++c p=? a=? b=? c=? p= 13, a=3, b=9 ,c=1
q= --a + b++ + ++c q=? a=? b=? c=? p=13 a=3 , b=10,c=2
r = a-- + --b + c++ r=? a=? b=? c=? p=14, a=4, b=9, c=3
What is the output??
#include<stdio.h>
int main()
{ 1)3
2) Compile time error
int x, y; 3) 2
x = 5; 4)None of these
y = x++ / 2;
printf("%d", y);
return 0;
}
What is the output??

#include<stdio.h>
int main() 1) Compile time error
{ 2) 29
3) 28
int a=3, b=9; 4) None of these
printf("%d ", ++(a*b+1));
return 0;
}
Work it out!!
#include<stdio.h>
int main()
{ a) a = 1, b = 1
b) a = 2, b = 1
int a = 1, b = 1, c; c) a = 1, b = 2
c = a++ + b; d) a = 2, b = 2
printf("%d, %d", a, b);
}
#include<stdio.h>
int main()
{
a) 6
int i = 2;
b) 5
int j = ++i + i; c) 4
printf("%d\n", j); d) Compile time error

}
2. Based on type of operation
 Arithmetic operators
 Relational operators
 Logical operators
 Assignment operators
 Increment and Decrement operators
 Conditional operator
 Bitwise operators
 Special operators
Arithmetic operators
Arithmetic operations

 Integer Arithmetic
 Real Arithmetic
 Mixed mode Arithmetic
Integer Arithmetic
 When the both the operands are integer type in a single arithmetic
expression its called integer expression and the operation called
integer arithmetic

 Example:
int a=10, b=4;
a+b=14
a-b=6
a*b=40
a/b=2 (10/4=2.5 - decimal part truncated)
a%b=2 (remainder of division)
Write a C Program , taking two integer values as 10 and 2,
demonstrate the integer arithmetic operations by
Printing the following on the monitor
10+2=12
10-2=8
10*2=20
10/2=5
10 % 2 =0
#include<stdio.h> OUTPUT
void main() 10 + 2= 12
{ 10-2=8
int c,d,e,f,g; 10*2=20
int a=10,b=2; 10/2=5
c = a+b; 10 % 2=0
d=a-b;
e=a*b;
f=a/b;
g=a%b;
printf("%d + %d= %d \n",a,b,c);
printf("%d-%d=%d\n", a, b,d);
printf("%d*%d=%d\n", a, b,e);
printf("%d/%d=%d\n", a,b,f);
printf("%d %% %d=%d\n", a,b,g);
}
Write a C program to use integer
arithmetic to convert a given number of
days into months and days
/* Program to show integer arithmetic */
#include<stdio.h>
void main()
Output
{
Enter the number of days:265
int days,month,rem_day;
Months = 8
printf(“Enter the number of days :");
Days = 25
scanf("%d",&days);
month = days / 30;
rem_day= days % 30;
printf(“Months = %d \n Days = %d", month,
rem_day);
}
Real Arithmetic
 An arithmetic expression involving only real operands is called real
arithmetic.
 Example:-
float x, y, z;
x= 6.0 / 7.0= 0.857143
y= 1.0 / 3.0= 0.333333
z= - 2.0 / 3.0= -0.666667
The operator % cannot be used with real operands
Mixed Mode Arithmetic
 When one of the operand is real and the other is integer, the expression is
called mixed mode expression.
 Example:-
int a=15;
float b=10.0;
a/b=15/10.0=1.5 (if result is float variable)

 Where as 15/10=1 (if result is int variable)


Relational Operators
-returns 1 when operation is true
-returns 0 when operation is false

Operator Meaning Example

< Less than Age<18

> Greater than Height > 5.3

<= Less than and equal to marks<= 40

>= Greater than or equal to Temp>=98.6

== Equal to Grade==100

!= Not equal to Marks!=40


Program to show working of Relational
operators.
Output
#include<stdio.h>
10<20=1
void main()
10>20=0
{
10<=20=1
int a=10,b=20;
10>=20=0
printf("%d<%d =%d \n",a,b,a<b);
10==20 = 0
printf("%d>%d =%d\n",a,b,a>b);
10!=20 = 1
printf("%d<=%d =%d\n",a,b,a<=b);
printf("%d>=%d =%d\n",a,b,a>=b);
printf("%d==%d =%d\n",a,b,a==b);
printf("%d!=%d =%d\n",a,b,a!=b);
}
Logical Operators
 Used when we need to test multiple conditions in order to make a decision.
 Logical operators are used for combining simple conditions to make complex conditions.
 Logical operators are used for combining two or more expressions. Since the output of
expression is true or false
&& is AND eg : if ( x > 5 && y < 6 )
|| is OR eg: if ( z == 0 || x > 10 )
a b a&&b a||b
! is NOT eg : if (! (bob > 42) )
0 0 0 0

0 1 0 1

1 0 0 1

1 1 1 1
int j=0 , m=1 , n=-1;
float x=2.5, y=0.0;

Expression Result
j && m 0
(j<m)&&(n<m) 1
(m+n)||(!j) 1
((j<=10)&&(x>=1))&&m 1
((x*y)<(j+m)) || m 1
#include<stdio.h> Output
void main() d=0
{ d=1
int a=10,b=11,c=12,d;
d=(a<b)&&(c<b);
printf(" d = %d",d);
d= (a<b)||(c<b); Operator Priority
printf("\n d = %d",d); ! 1

} && 2
|| 3
Assignment operators(Shorthand)
 Used to assign the result of an expression to a variable.
v op=exp; v=v op exp
v: variable
exp : expression
op : arithmetic operator
a= a+b can be written as a+ = b
a=a*b can be written as a *= b
a=a/b can be written as a /= b
a=a-b can be written as a -= b
a=a/(n+1) can be written as a/=n+1
a=a%b can be written as a % =b
Program to demonstrate assignment operators
#include<stdio.h>
void main()
{
Output
int a=5,b;
b= 5
b=a;
b=10
printf("\n b= %d",b);
b=5
b+=a;
b=25
printf("\n b=%d",b);
b=5
b-=a;
printf("\n b=%d",b);
b*=a;
printf("\n b=%d",b);
b/=a;
printf("\n b=%d",b);
}
Conditional Operator
 Also called Ternary operator.

Syntax : <expression> ? Value1 : value2;

? : conditional operator
Expression is relational expression
Value 1 is assigned when expression is True
Value 2 is assigned when expression is False
c= a>b ? a:b;
Output
#include<stdio.h>
c=5
void main()
{
int a=5 ,b=4,c;
c=a>b?a:b;
printf("c=%d",c);
}
Write C program to find largest of 3
numbers using ternary operators
#include<stdio.h> Output
void main() enter the values of 3 numbers6

{ 45

int a,b,c; 6

int result; 45 is biggest

printf("enter the values of 3


numbers");
scanf("%d%d%d",&a,&b,&c);
result = (a>b && a>c)?a:(b>c)?b:c;
printf("%d is biggest ",result);
}
Write a C program to find if a number is
odd or even using ternary operator
Bitwise Operator
 This helps in performing bit level operations
Decimal to binary Binary to decimal
Bitwise Operators in C
29

21
Left shift operator (<<)
 Shifts all bits towards left by a certain number of specified bits
12 << 2
0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 (Binary 12)

0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 (Binary 48)
12 << 2 = 48

Right shift operator (>>)


 Shifts all bits towards right by a certain number of specified bits.
12>>2
0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 (Binary 12)

0000 0000 0000 0 0 1 1(Binary 3)


Complement (~)
~35
0 0 1 0 0 0 1 1
1 1 0 1 1 1 0 0

 The bitwise complement of 35 is -36 instead of 220 !!! The reason for this is the
system uses two’s complement when performing complement operation
 One’s complement : inverts all the bits
 Two’s complement: one’s complement +1
 For any integer n bitwise complement of n is –(n+1)
 35 : 00100011 (binary) 11011100 (one’s complement) : 210
 210 : 11011100 -(00100011(one’s complement) + 1) 00100100= -36
 Therefore ~n = -(n+1)
 ~(-n)=-(-n+1) a=-10 b=~a -(-10+1)=9
Program to demonstrate bitwise operation
#include<stdio.h>
void main()
{
int a=60 ,b=13;
OUTPUT:
int c;
bitwise and : c= 12
c=a&b;
bitwise or : c=61
printf("\n bitwise and : c= %d",c);
bitwise complement : c=-61
c=a|b;
bitwise xor : c=49
printf("\n bitwise or : c=%d",c);
left shift : c=240
c=~a;
right shift : c=15
printf("\n bitwise complement : c=%d",c);
c=a ^ b;
printf("\n bitwise xor : c=%d",c);
c=a<<2;
printf("\n left shift : c=%d",c);
c=a>>2;
printf("\n right shift : c=%d",c);
}
Special Operator
1. Comma Operator
2. sizeof() Operator
3. Address Operator
4. Dot Operator

Comma Operator – Used to link related expression together. Eg int a,b,c;


Sizeof()- this returns size of an operand. Mianly used to determine length of
arrays , structure
Summary - Operators
Operator precedence and associativity
 An arithmetic expression without parentheses will be evaluated from left to
right using rules of precedence
*/% Highest priority

+- Least Priority
Example : x= 9-12/3+3*2-1
Step1: 12/3 = 4 ; 3*2=6 ; 9- 4+6-1
Step 2:9-4 ; 5+6-1
Step 3: 5+6; 11-1
Step 4: 10
Expression with Parentheses
Evaluate the expression 9-12/(3+3)*(2-1)
9-12/(3+3)*(2-1)
Step 1: 9-12/6*1
Step 2:9-2*1
Step 3: 9-2
Step 4: 7
Evaluate : 17-8/4*2+3- ++a assuming a=5

17-8/4*2+3- ++a
17-8/4*2+3 – 6
17-2*2+3-6
17-4+3-6
13+3-6
16-6
10
Solve:a+2 > b && !c||a !=d&&a-2<=e

where a=11 b=6 c=0 d=7 e=5


11+2>6 && !0||11 != 7 && 11-2<=5
11+2>6 && 1||11 != 7 && 11-2<=5
Brackets
13>6 && 1 || 11 !=7 && 11-2<=5 Unary Operators
Arithmetic operation
13>6 && 1 || 11 !=7 && 9<=5
Relational Operation
1 && 1 || 11 !=7 && 9<=5 Logical Operation
1 && 1 || 1 && 9<=5
1 && 1 || 1 && 0
1 || 1 && 0
1 || 0 = 1
Type Cast & Type Conversion
 Type conversion is carried out when an expression has data of different types.
 It is a process of converting data of one type to another
 There are 2 ways in which this is done
1. Implicit type conversion 2. Explicit Type conversion

1. IMPLICIT TYPE CONVERSION : When the conversion is automatically carried out by


the compiler without the programmers intervention .
float b;
b=150;
printf(“b= %f”,b); Output : 150.000000
2. EXPLICIT TYPE CONVERSION

There will be instances when we would want to force a type conversion in a way
different than the automatic conversion.
SYNTAX: (type-name)EXPRESSION
Ex:
int female_students, total_students;
Ratio = female_students / total_students (decimal portion is lost and hence
doesn’t give a accurate result)

Ratio = (float) female_students / total_students ;


Some examples

Example Action
x= (int) 7.5 x=7
A=(int)21.3/(int)4.5 A= 21/4 = 5
B=(double)(sum/n) B will have result in double precision
Y= (int)(a+b) Result a+b is converted and stored in int form
Z=(int) a + b a is converted to int and then added to b
Types of errors
1. Syntax error : Each language has a set of rules to be followed while writing a
program. The errors that are obtained if the rules are not followed are called
syntax errors.
2. Logical error : Also known as Semantic error. When a program is compiled and
executed successfully and if the desired output is not obtained then the
program is said to have logical errors.
3. Runtime Error : This occurs when a program attempts to perform a task that
is not allowed. Eg : int b=0 ; c=a/b ;
Formatted & Unformatted Input / Output Statements

Standard I/O Library


#include<stdio.h> : scanf , printf , getchar, putchar
#include<conio.h> : getch , putch , clrscr

Stdio : Standard input output header file


Conio : Console input output header file

I/O functions
1. Unformatted I/O Function Ex : getch , putch
2. Formatted I/O Function ex: scanf , printf
getchar and putchar
getchar() : To read a character from the keyboard and store this character into
memory location. This function reads one character at a time
ch= getchar();
putchar() : To display a character stored in a variable on to the monitor. The
variable we intend to display needs to be passed as a parameter
putchar(ch);

#include <stdio.h> Output


void main() Enter a character. A
{
char c; Entered Character is : A
printf("Enter a character.");
c = getchar();
printf("\n Entered character is: ");
putchar(c);
printf("\n");
}
getch , getche and putch()
getch() : This function reads a character from the keyboard and copies it into
memory area, But the entered character will not be visible.
ch= getch();
getche() : this function reads a character from keyboard and copies it into
memory area. The character will be displayed on the screen
ch= getche() e : echo
putch() : This function outputs a character stored in the memory using a variable
on the monitor
putch(ch);
gets and puts
gets : is used to read a set of character from the keyboard
puts : is used to display a set of character on the screen

#include <stdio.h> Output


void main() Enter student’s name : ajay
{ The student’s name is ajay
char str[10];
printf(“Enter the student’s name: ");
gets(str);
printf(“The student’s name is : ");
puts(str);
}
Formatted Input
 scanf() : this function is used to read data of different types like int ,float,
char etc from the keyboard.
Syntax : scanf(“format specifier “,&var1,&var2…&varn);

Data Type Format Specifier Meaning


int %d Read a integer value
%u Reads a unsigned integer
float %f Floating point number
char %c Reads a character
%s Reads a string
double %lf Reads a long floating point
number
long int %ld Reads a long integer
Formatted Output
 printf() : This function is used to print or display different types of data such as int , float,
char etc on the screen
Syntax : printf(“ Format Specifier “,var1 , var2…..varn);
Field width specification for int :
Format specifier : %wd w: number of columns d: format specifier for int
Field width specification for float :
Format specifier : %w.xf
w: number of columns x: number of column used after decimal f: format specifier of float
Field width specification for float :
Format specifier : %w.xs
W: number of columns x : number of column reserved to print string in right justified manner
the rest is ignored
s = format specifier for string
#include <stdio.h>
void main()
{
int a=798;
printf("%5d \n",a);
printf("%-5d \n ",a);
printf("%2d\n",a);
printf("%0.5d",a);
getch();
}
#include <stdio.h>
int main()
{
float a=98.578;
printf("%7.2f \n",a);
printf("%-7.2f \n ",a);
printf("%2.2f\n",a);
printf("%1.0f \n",a);
printf("%0.3f\n",a);
return 0;
}
#include <stdio.h>
int main()
{
char a[30] = "computer science";

printf("%s \n",a);
printf("%5.10s \n ",a);
printf("%15.10s \n ",a);
}
Write a C program to find out if a triangle is equilateral or isosceles given the 3
sides of the triangle. Use Logical operator

Hint :

If a,b,c are the three sides of a triangle ,then the condition is


If(a==b) &&(b==c) &&(c==a) Then the triangle is called equilateral triangle
If(a==b) II(b==c) II (c==a) Then the triangle is called isosceles triangle

You might also like