POP Using C - Module 2
POP Using C - Module 2
Module – 2
Operators and Expressions in C
Operators and expressions in C:
- Operators in C: arithmetic, relational, equality,
- logical, assignment,unary,
- conditional, bitwise operator, Increment and decrement operator,
- Conditional Operator, operator precedence,
- keywords and identifiers,
- Type conversion and typecasting.
Decision control and Looping statements:
- Introduction to decision control,
- Conditional branching statements,
- Iterative statements,
- Nested loops,
- break and continue statements,
- goto statement.
Prepared By –
Prof.DIVYA.H.N. B.E,M.Tech,(Ph.D )
Asst.Professor,
Department of CSE, DSATM
Introduction
In the previous chapter we studied Alphabets of C ,how these alphabets are used to obtain
meaningful words called Tokens , and various types of Tokens .We also discussed about the
variables and how some of the keywords can be used to define the Type of the variables .Now ,
we will see how these variables and constants are joined together using operators to obtain the
expression and evaluate the expressions .
1.Operators
+ , - , * , / , are some of the Operators . + means Add ; - means Subtract ; * means Multiply
and so on .
Eg 1 : 10 + 20
// Here 10 and 20 are called Operands and + is an Operator . Since there are Two Operands ,
the Operator + is called Binary Operator //
Eg 2 : - 100
// Here 100 is an Operand and - is an Operator . Since the Operator ‘-‘ is associated with Only
Operand it is called Unary Operator //
C language includes large number of Operators . The Operators in C can be classified based on
The Operators are classified into four major categories based on the number of Operands
shown below :
1.Unary Operators
2.Binary Operators
3.Ternary ( ?:) Operators
4.Special Operators : comma , size of etc.
An Operator which acts on Only one Operand to Produce the result is called Unary Operator .
In this expressions involving Unary Operator , the operators precede the Operand .
Eg : -10 , -a , *b , &c , ~d etc .
1.1.2.Binary Operators
An Operator which acts on Two Operands to produce the result is called Binary Operator.
In an Expression involving a Binary Operator, the Operator is placed between Two Operands
An Operator which acts on Three Operands to Produce the result is called Binary Operator. This
Operator is also called Conditional Operator .
Eg : a ? b : C
The Operations that are used to Perform Arithmetic Operations such as Addition
,subtraction ,Multiplication etc are Arithmetic Operators .
1.2.2.Assignment Operators Before Manipulating the data , the data as to be stored in memory
. Now the Question is “How to store the data in memory ?’ .This is where the Asssignment
Operator is used .
Eg Statements Results
1 a=b; Store the Value into b
2 area = l*b ; Compute the Product and store the value into area
3 Pi = 3.1416 ; Store the number 3.1416 using the variable pi
4 a = =b ; Error = = is relational Operator (used for compare not to
copying)
5 a = b*10 ; Error No semicolon at the end
6 10 + b = c ; Error Expression not allowed on LHS Of assignment Operator
Pre increment ( ++ a) : if the increment operator (++) is placed before the Operand
,then the Operator is called Pre increment Operator . As the name indicates pre increment
means increment before the Operand Value is used . So Operand value is incremented
by 1 .
Post increment (a++) . if the increment operator (++) is placed After the Operand ,then
the Operator is called Post increment Operator . As the name indicates pre increment
means increment After the Operand Value is used, the Operand value is incremented
by 1 .
In the above table ; If initial value of a is 20 , in both the cases after Executing , the value of a
will be 21
Decrement Operators
In the above table ; If initial value of a is 20 , in both the cases after Executing , the value of a
will be 21
*Note*
In pre-decrement, first the value of the variable is decremented after that the
assignment or other operations are carried. In post-decrement, first assignment or other
operations occur, after that the value of the variable is decremented.
Eg :
a- -;
--a;
a = a - 1;
a -= 1; are all same if used independently.
1.2.4.Relational operators
The Relational Operators also called Compare Operators are used to Compare Two Operands .
They are used to find the Relationship between Two operands hence are called Relational
Operators .
The Relationship between these two Operands results in either True (always 1 ) or False
(always 0).
Operator Meaning
< Less Than
> Greater Than
= Equal To
!= Not Equal To
<= Less Than or Equal To
>= Greater Than or Equal To
1.2.5.Logical Operators
The Logical Operators are used to combine two or more Relational Expressions.
Eg : if a = = b && b= = c ,then the Triangle is Equilateral . Here Two Expressions are Combined
together by a Logical && Operator .
Since the Output of Relational Expressions is True or False , the Output of Logical Expressions
is also True or False .
1.2.6.Conditional Operator ( ?: )
An Operator that Operates on three Operands is called Ternary Operator (Conditional Operator).
Syntax :
Here, exp1 is evaluated first. If it is nonzero (true), then the expression exp2 is evaluated and
becomes the values of the expression.
If exp1 is false, exp3 is evaluated and its value becomes the values of the expression.
Note that only one of the expressions either exp2 or exp3 is evaluated.
For example,
a=10; b=34;
True
max=(a > b) ? a: b;
False
In this example, max will be assigned the value of b because the condition is false. So, exp3 (b)
is evaluated and its value is assigned to max .
The Data is stored in the memory in terms of Binary Digits i.e, 0’s or 1’s . Sometimes , it may be
necessary to manipulate these bits . The Operators that are used to manipulate the bits are called
Bit Wise Operators .
Operator Description
~ Bit wise negative
<< Left shift
The Comma Operator represented as a comma ( , ) accepts two Operands and it is used to
combine two or more statements into a single statement . Thus , Compact statements can be
written using comma operator .
The statements are executed one by one from left to right and hence it is left associative operator.
Eg : Consider the statements
temp=a;
a=b;
b=temp;
Syntax : sizeof
(Operand)
Eg ;
Sizeof(char) 1bytes
Sizeof(int) 2bytes
Sizeof(float) 4bytes
The Equal-to-Operator ( = = ) returns True if both Operands have the same value ; otherwise it
returns False .
The not-Equal-to Operator ( != ) returns True if the Operands don’t have the same value ;
otherwise it returns False
1.2.9.Type Casting: In typing casting, a data type is converted into another data type by the
programmer using the casting operator during the program design. In typing casting, the
destination data type may be smaller than the source data type when converting the data type to
another data type, that’s why it is also called narrowing conversion.
Keywords
The words which have predefined meaning in C language are called Keywords .Since they are
reserved for specific purpose in c language ,they are also called reserve words . The keywords
have some specific purpose in c language and hence cannot be used as variable names
,function names etc
*Note *
1.The meaning of the keywords cannot be changed by the user .
2.All keywords should be written in lower case letters .
3.If we use Capital letters they are treated as just identifiers
1.2.12.Identifiers
An Identifier is a word consisting of sequence of one or more letters or digits along with a
special character “_”(underscore).
Eg : The letters are the characters from ‘A’ to ‘Z’ and ‘a’ to ‘z’ .The Digits are the characters
from 0 to 9.
Normally an Identifier starts with a letter or an underscore and followed by any number of
letters or digits or underscore .
•
Eg : variables name: sum,i,x,my_marks &
Function names : main,printf etc
In C Language , each Operator is associated with Priority Value . Based on the priority , the
Expressions are evaluated . The Priority of each Operator is Pre – defined in C language .
The Pre-defined priority or Precedence order given to each of the Operator is called
Precedence of Operator .
The Operations that are carried out based on the precedence of Operators are Called
Hierarchy of Operations .
Associativity of Operators
If all the Operators in an Expresssion have equal priority , then the Direction order choosen ( left
to right evaluation or right to evaluation ) to evaluate an expression is called Associativity of
Operators .
They are Classified into Two Categories based on the Direction of Evaluation Chosen as shown
below :
1.Left to Right Associativity ( Left Associative) ; Eg : All Binary Arithmetic , Logical and
Relational Operators .
In the Expression ,if there are two or more Operators having the same priority and evaluated
from left to right , then the Operators are called Left To Right Associative Operators .
Eg : 8+4+3
12+3
In the Expression ,if there are two or more Operators having the same priority and evaluated
from right to left , then the Operators are called Left To Right Associative Operators.
Soln : 2* ( ( a % 5 ) * ( 4 + (b – 3) / ( c + 2 ) ))
=2* ( ( 8 % 5 ) * ( 4 + ( 15 – 3) / ( 4 + 2 ) ) )
=2* ( 3 * ( 4 + ( 15 – 3) / ( 4 + 2 ) ) )
=2* ( 3 * ( 4 + 12 / ( 4 + 2 ) )
=2* ( 3 * ( 4 + 12 / 6 ) )
=2* ( 3 * ( 4 + 2 ) )
=2* ( 3 * 6 )
=2 * 18
= 36
Hierarchy of Operator ( On Relational Expressions )
5 < = 10 – 5 + 0 - 20 = = 5 > = 1 ! = 20
5<=5 + 0 - 20 = = 5 > = 1 ! = 20
0 ==5 > = 1 ! = 20
0 == 1 != 20
0 != 20
Evaluate the Expression : a + 2 > b && ! c || a ! = d & & a – 2 < = e ; where a=11;
b=6;c=0;d=7 & e = 5
1 || 0
Evaluate :
a) a+2 > b || ! c && a ==d || a-2 < = e ; where a = 11 , b= 6 , c= 0 , d = 7 ,e =5.
b) 10!=10||5<4&&8
It can be written as
x* =(y+3)
can be interpreted as ; x = x * ( y +3)
x = 10 * ( 5+3)
x = 10 * 8
x=80
a + b * = c - = 5 ; where a = 1 ; b = 3 and C = 7.
a+b*=c-=5
c=c–5
c=7–5
c =2
a+b*=2
a+=b=b*2
b=3*2
b=6
a+ = 6
a=a+6
a=1 +6
3. Statements
3.1.Expression Statement
An expression followed by a semicolon is called Expression statement
Eg : area=l*b;
Sum=sum+i;
J++;
Printf(“\n enter the number”);
Scanf(“%d”,&n);
3.2.Compound Statement
✓ A sequence of statement enclosed within a pair of braces { } is called compound
statement .
✓ Even if a single statement is present within the braces ,it is treated as a compound
statement .
✓ The Compound statement is also called block statement .
eg1 :
{
Printf(“\n area=%ld”,l*b);
}
3.3. Control statements in C are programming constructs that are used to control the flow of
execution in a program.
They allow a programmer to specify conditions that determine which statements are
executed and which are skipped, to loop through statements until a condition is met, or to jump
to a different part of the program.
Eg ;
In Sequential control , all the statements are executed in the order in which they are written .
However , a set of statements may have to be executed only when certain condition is met . A set
of statements may have to be skipped during execution when some other condition is met
.sometimes without any condition , the control may be transferred to some other place in the
program .These statements that transforms the control from one place to other place in the
Program with or without any condition are called Branch Statements .
Normally , all the statements are executed one after the other .However sometimes,the user
wants to execute certain statements when some condition is met or the user may skip the
execution of some statements when some other condition is met . These statements that transfer
control from one place to other place so as to execute a set of instructions if some
condition is met or skip the execution of some statements if the condition is not met are
called conditional branch statements .they are also called selection statements or decision
statements . Simple if (single selection ) .
Syntax ;
• If one set of activities have to be performed when an expression is evaluated to true and
another set of activities have to be performed when an expression is evaluated to false
,then if-else-statement is used .
The if-else statement is a simple selection /decision statement that is used when we must choose
between two alternatives .Hence it is also called Two-way Decisions /Selection statement.
4.1.3.Nested –if
Advantages
1. There are situations involving series of decisions where we are forced to use an if or if-
else in another if or if-else statement.In such situations , nested-if-statements are used .
Eg ;
4.1.3.Else-if ladder
• An else-if ladder is a special case of nested-if statement where nesting take place only in
the else part .
• When an action has to be selected based on range of values , then this statement is used
.so it is called multi-way decision/selection statement .
• The orderly nesting of if-else-statement only in the else part is called else-if-ladder .
Example :
The Switch statement is a control statement used to make a selection between many
alternatives.
❑ Advantages
• Improves readability of the program
• More structured way of writing the program .
❑ Disadvantages
• Used only if the expressions used for checking the conditions results in Integer
value(char is also allowed ).If the result of expression is not integer value,switch
statement cannot be used .
• Cannot be used when a selection is based on a range of values
*Note*
When break statement is executed ,the control comes out of the switch statement .
Eg;/*Prog to compute -
• Calculator function using switch
• To check an alphabet vowel or not
• The sequential statements are executed one after the other .But , if the programmer wants
to transfer the control from one point to other in the Program ,the goto statement can be
used .
• Using this statement ,control can be transferred from one statement to the specified
statement without any condition(conditionally).
• Syntax:
goto label;
❑ Disadvantages
• Using goto,the code is difficult to read and understand .
• The usage of goto results in unstructured programming.
• It is not good programming style .
*NOTE * As far as possible use of goto is avoided in all subsequent programs.
The break statement is jump statement which can be used in switch statement and loops .
❑ The break statement works as shown below :
✓ The break statement in switch statement causes control to terminate switch statement and
the statement following switch statement will be executed .
✓ Usually in any case , the break statement will be the last statement.
✓ If break is executed in a loop(such as for/while/do-while),the control comes out of the
loop and the statement following the loop will be executed .
Eg : During processing of student records , it may be necessary to exclude student names whose
marks are less than or equal 50.In such case , a test is made to see whether the marks scored is
less than or equal to 50.If so part of the program that processes the student details can be skipped
using Continue .But the execution continues with next iteration of the loop .
Syntax
4.2.4.return statement
Eg :
• If a function is not returning any value ,use the return keyword as shown ;
return ;
• If a function is returning any value ,use the return keyword as shown;
return value ;
A set of statements may have to be repeatedly executed for a specified number of times or till a
condition is satisified . The Statements that help us to execute a set of statements repeatedly are
called Looping Constructs or Loop Control statements .
A for loop is a control statement using which the programmer can give instructions to the
computer to execute a set of statements repeatedly for a specified number of times .Since it is
required to specify how many times a set of statements have to be executed ,it is also called
counter-controlled loop .
2.Second expression exp2 is evaluated to True / False . If it is evaluated to False , the control
comes out of the loop without executing the body of the loop and the A-statements following the
for loop are executed .
3.If exp2 is evaluated to True , the body of the loop is executed . After executing the body of the
loop , control goes back and exp3 is executed .
*NOTE*
a) Exp2, the body of the loop and exp3 are repeatedly executed as long as exp2 is evaluated to
True. Once the exp2 is evaluated to FALSE ,the control comes out of the loop and the A-
statements that appear after the for loop are executed .
b) The for loop is always used when we know initial value , final value and Updating value . The
Updating value can be constantly incremented or decremented .
#include<stdio.h>
Void main()
int n,i ;
scanf(“%d”, &n);
for(i=0;i<n;i++)
Printf(“%d”,i);
#include<stdio.h>
Void main()
int n,i ;
scanf(“%d”, &n);
for(i=0;i<n;i- -)
Printf(“%d”,i);
#include<stdio.h>
Void main()
int n,fact,i ;
scanf(“%d”, &n);
fact = 1 ;
for(i=0;i< =n;i+ +)
fact* = i ;
Printf(“%d ! = %d \n ”, n , fact );
A while loop is a control statement using which the programmer can give instructions to the
computer to execute a set of statements repeatedly as long as specified condition is satisfied .
Once the specified condition is false , control comes out of the loop .
The following sequence of operations are carried out after executing B – Statements that are
present before the while-loop
a)The initialization for the while loop are done first . Theloop controlled variable is also
initialized .
b)Then the expression is evaluated to True / False . If it’s evaluated to False , the control comes
out of the loop without executing the body of the loop and A-statements that are present after the
while loop are executed .
c)If the expression is evaluated to TRUE,the statements inside the body of the loop are executed .
e)Thus the body of the loop is repeatedly executed as long as expression is evaluated to TRUE ,
Once the expression is evaluated to False ,the control comes out of the loop and A-statements
following while loop are executed .
f) Since a set of statements have to be repeatedly executed based on the conditions or till an
event has occurred,the while loop is also called condition-controlled loop or event – controlled
loop .
Void main()
int n,sum,i;
scanf(“%d”,&n);
sum = 0 ;
i= 1;
sum = sum + i ;
i++ ;
do-while loop is similar to a while loop and used when a set of statements have to be
repeatedly executed at least once until a certain condition is reached .when we do not know
exactly how many times a set of statements have to be repeated ,do while can be used .
Since the expression is evaluated to True or False at the end of the do-while loop , the do-
while loop is also called exit-controlled loop .
Working ;
The following sequence of Operations are carried out after executing the B-statements that
appear just before the do-while loop.
a ) The statements inside the body of the do-while loop are executed one after the other .
b) Then , the expression is evaluated . If the expression is evaluated to True , the body of the
loop is executed again and the process is repeated . The moment expression is evaluated to False
, control comes out of the do-while and A-statements that appear the do-while loop are executed .
#include<stdio.h>
Void main()
int sum , n ,i ;
scanf(“ %d”,&n);
i=1;
do
sum = sum + i ;
i++;
While ( i < = n) ;