POP Module-2
POP Module-2
Arithmetic Operators:
+ addition
- subtraction
* Multiplication
/ Division
All these Arithmetic operators in C are binary operators which means they operate on two
operands.
The following table shows all the arithmetic operators supported by the C language. Assume variable A holds 10
and variable B holds 20, then –
The following table shows increment and decrement operator supported by the C language. Assume
variable A holds 10 ,then –
Postfix Expressions:
The postfix expression consists of one operand followed by one operator.
Prefix Expression:
In prefix expression, the operator comes before the operand.
Assignment operators:
Assignment operators are used to assign the result of an expression to a variable. There are
several different assignment operators in C. All of them are used to form assignment expressions which assign the
value of an expression to an identifier. The commonly used assignment operator is ‗=‘ operator. The general
syntax is:
Where identifier generally represents a variable and expression represents a constant, a variable or a more
complex expression.
For example:
x=y+1;
a=2*c;
rate= 45;
delta= 0.001
sum=a+b;
Note that the assignment operator = and the equality operator == are distinctly different. The assignment operator
is used to assign a value to an identifier, whereas the equality operator is used to determine if two expressions
have the same value. These operators cannot be used in place of one another.
In addition to the usual assignment operator ‗=‘ C has a set of assignment operators called shorthand operators.
Some of the shorthand operators are listed below:
=
+=
-=
*=
/=
%=
>>=
<<=
&=
^=
|=
The following table lists the shorthand assignment operators supported by the C language –
Relational operators:
We often compare two quantities and depending on their relation, to take certain decisions. For example, we may
compare the age of two persons, or the price of two items, and so on. These comparisons can be done with the
help of relational operators.
C supports six relational operators in all. These operators and their meanings are shown below:
Operator Meaning
< is less than
> is greater than
<= is less than or equal to
>= is greater than or equal to
Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 5
== is equal to
!= is not equal to
Given below are some examples of simple relational expressions and their values:
4.5<=10 TRUE
4.5>10 FALSE
-35>=0 FALSE
Relational expressions are used in decision statements such as, if and while to decide the course of action of a
running program.
The following table shows all the relational operators supported by C language. Assume variable A holds 10 and
variable B holds 20 then −
== Checks if the values of two operands are equal or not. (A == B) is not true.
If yes, then the condition becomes true.
> Checks if the value of left operand is greater than the (A > B) is not true.
value of right operand. If yes, then the condition
becomes true.
< Checks if the value of left operand is less than the (A < B) is true.
value of right operand. If yes, then the condition
becomes true.
>= Checks if the value of left operand is greater than or (A >= B) is not true.
equal to the value of right operand. If yes, then the
condition becomes true.
<= Checks if the value of left operand is less than or (A <= B) is true.
equal to the value of right operand. If yes, then the
condition becomes true.
Logical operators:
In addition to the relational operators. C has the following three logical operators.
&& logical AND
|| logical OR
! logical NOT
The logical operators && and || are used when we want to test more than one condition and make decisions.
Logical NOT
Op !Op
0 1
1 0
Following table shows all the logical operators supported by C language. Assume variable A holds 1 and
variable B holds 0, then −
Bitwise Operators:
In arithmetic-logic unit (which is within the CPU), mathematical operations like: addition, subtraction,
multiplication and division are done in bit-level. To perform bit-level operations in C programming, bitwise
operators are used.
Operators Meaning of operators
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
<< Shift left
>> Shift right
Bitwise AND operator in C programming.
The output of bitwise AND is 1 if both the corresponding bits of operand is 1. If either of bit is 0 or both bits are
0, the output will be 0. It is a binary operator (works on two operands) and indicated in C programming by &
symbol.
Example: Let us suppose the bitwise AND operation of two integers 12 and 25.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bit Operation of 12 and 25
00001100
& 00011001
________
00001000 = 8 (In decimal)
As, every bitwise operator works on each bit of data. The corresponding bits of two inputs are check and if both
bits are 1 then only the output will be 1. In this case, both bits are 1 at only one position,i.e, fourth position from
the right, hence the output bit of that position is 1 and all other bits are 0.
//program to illustrate the use of bitwise AND operator
#include<stdio.h>
void main()
{
int a=12,b=25;
printf("a&b=%d",a&b);
}
Output:
a&b=8
Bitwise OR operator in C
The output of bitwise OR is 1 if either of the bit is 1 or both the bits are 1. In C Programming, bitwise OR
operator is denoted by |.
Example: Let us suppose the bitwise OR operation of two integers 12 and 25.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Output:
a|b=29
Output:
a^b=21
2's Complement
Two's complement is an operation on binary numbers. The 2's complement of a number is equal to the
complement of that number plus 1.
In the above diagram, you can notice that whenever we shift the number one position to right, the output value
will be exactly number / 2.
If I shift 14 by 1 position to the right, output will be 14 / 2 = 7. i.e 14/2 = 7
Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 11
If I shift 14 by 2 position to the right, output will be 14 / 4 = 3. i.e 14/4 =3.5 since it‘s an integer, fractional part
will not be considered.
In general, if we shift a number by n times to right, the output will be number / (2n).
//program to illustrate the use of bitwise right shift operator
#include<stdio.h>
void main()
{
int a=14;
printf("a>>2=%d",a>>2);
}
Output:
a>>2=3
The operator ? : works as follows: expression1 is evaluated first. If it is nonzero (true), then the expression2 is
evaluated and becomes the value of the expression. If expression1 is false, expression3 is evaluated and its value
becomes the value of the expression. Note that only one of the expressions (either expression2 or expression3) is
evaluated.
The conditional operator is kind of similar to the if-else statement as it does follow the same algorithm as of if-
else statement but the conditional operator takes less space and helps to write the if-else statements in the
shortest way possible.
For example, consider the following statements
x=3;
y=15;
z=x>y?x:y;
In this example, z will be assigned the value of y. This can be achieved using the if..else statements as follows:
if (x>y)
Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 12
z=x;
else
z=y;
Example:
/*program to find smallest of two given numbers using conditional operator*/
#include<stdio.h>
void main( )
{
int a,b,s;
printf("enter two numbers");
scanf("%d%d",&a,&b);
s=a<b?a:b;
printf("smallest number is %d",s);
}
Output:
enter two numbers
53
smallest number is 3
Special Operators:
Comma Operator:
Comma operators are used to link related expressions together.
For example: int a,c=5,d;
Expression:
An expression is a combination of operators, constants and variables. An expression may consist of one or
more operands, and zero or more operators to produce a value.
Similarly, during modulo division , the sign of the result is always the sign of the first operand(the dividend)
That is
-14 % 3 =-2
-14 % -3= -2
14 % -3=2
Real Arithmetic
An arithmetic operation involving only real operands is called real arithmetic. A real operand may assume
values either in decimal or exponential notation. Since floating point values are rounded to the number of
significant digits permissible, the final value is an approximation of the correct result. If x, y, and z are floats, then
we will have:
x=6.0/7.0=0.857143
y= 1.0/3.0 =0.333333
z= -2.0/3.0= -0.666667
Thus
15/10.0=1.5
where as
15/10=1
Precedence and Associativity:
Precedence is used to determine the order in which different operators in a complex expression are
evaluated. Associativity is used to determine the order in which operators with the same precedence are evaluated
in a complex expression. Another way of stating this is that associativity determines how operators with the same
precedence are grouped together to form complex expression. Precedence is applied before associativity to
determine the order in which expressions are evaluated. Associativity is then applied, if necessary.
Use of parentheses:
Parentheses are used if the order of operations governed by the precedence rules are to overridden.
In the expression with a single pair of parentheses the expression inside the parentheses is evaluated FIRST.
Within the parentheses the evaluation is governed by the precedence rules.
For example, in the expression:
a * b/(c+d * k/m+k)+a
the expression within the parentheses is evaluated first giving:
c+dk/m+k
After this the expression is evaluated from left to right using again the rules of precedence giving
ab/c+dk/m+k +a
If an expression has many pairs of parentheses then the expression in the innermost pair is evaluated first, the
next innermost and so on till all parentheses are removed. After this the operator precedence rules are used in
evaluating the rest of the expression.
((x * y)+z/(n*p+j)+x)/y+z
xy,np+j will be evaluated first.
In the next scan
xy+z/np+j +x
Will be evaluated. In the final scan the expression evaluated would be:
(xy+ z/np+j+x)/y +z
Associativity:
Associativity can be left-to-right or right-to-left. Left-to-right associativity evaluates the expression by
starting on the left and moving to the right. Conversely, right-to-left associativity evaluates the expression by
proceeding from the right to the left.
Left-to-right Associativity:
The following shows and example of left-to-right associativity. Here we have four operators of the same
precedence (* / % *)
3 * 8 / 4 % 4 *5
Associativity determines how the subexpressions are grouped together. All of these operators have the
same precedence. Their associativity is from left to right. So they are grouped as follows:
Type Conversion:
Implicit Type Conversion:
When the types of the two operands in a binary expression are different, C automatically converts
one type to another. This is known as implicit type conversion.
Example: int i =1234;
float d;
d=i; // value of d is 1234.0
Explicit Type Conversion:
C allows mixing of float with integers in expressions. In such cases integers are converted to float
before computation. C provides explicit type conversion functions using which a programmer can intentionally
change the type of expressions in an arithmetic statement. This is done by a unary operator called a cast. If we
write (type_name) expression the expression is converted to the type_name
Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 19
For example
(float)(integer expression or variable name)
then the integer expression or variable name is converted to float. If we write:
(int)(float expression or variable name)
then the float expression or variable name is converted to integer.
X = (int) 2.3 ;
Y = (float) 234;
Two-way Selection:
The basic decision statement in the computer is the two-way selection. The decision is
described to the computers as a conditional statement that can be answered either true or false. If
the answer is true, one or more action statements are executed. If the answer is false, then a
different action or set of actions is executed. Regardless of which set of actions is executed, the
program continues with the next statement after the selection.
The C has two different Two-way selections, the if statement, the if-else statement
if Statement:
The general form of if statement looks like
The keyword if tells the compiler if the condition is true, then statement should be executed.
Suppose if the condition is false, then statement has to be skipped.
Boolean False
Condition
True
Statements
In the preceding syntaxes, a simple or compound statement (block of statements) is executed when
the condition expression given in the if statement is turn out to be true. Otherwise, the program
control passes to the next statement. If the condition expression is false then the C compiler does
not do anything. Note that the condition expression given in parentheses, must be evaluated as true
(non-zero value) or false (zero value). In addition, a compound statement must be provided by
opening and closing braces.
Example: Given two integer numbers, find out the larger of them.
#include <stdio.h>
main()
{
float x, y;
printf(― input two numbers\n‖);
scanf(―%f %f ―, &x, &y);
if ( x > y)
printf(― x is big\n‖);
if (y > x)
printf(―y is big\n‖);
}
If the condition is true, the statement1 is executed. If the condition is false, then statement2 under
else part is get executed.
The if-else statement executes a simple or compound statement when the conditional
expression provided in the if statement is true. It executes another simple or compound statement,
followed by the else statement, when the conditional expression is false. The flowchart for the if-
else is shown below:
Statement2 Statement1
#include <stdio.h>
main()
{
int x;
printf(―input an integer\n‖);
scanf(―%d‖,&x);
if ((x % 2) == 0)
printf(―it is even number\n‖);
else
printf(―it is odd number\n‖);
}
Compound Statements:
A compound statement is a unit of code consisting of zero or more statements. It is
also known as block. A compound statement consists of an opening brace, an optional declaration
and definition section and an optional statement section, followed by a closing brace.
Nested if Statements:
The term nested if statements means one if statement contains another if statement. The
control of a program moves into the inner if statement when the outer if statement is evaluated to
be true. When an if…else is included within an if… else, it is known as a nested if statement. The
following flowchart illustrates the nested if statement. There is no limit to how many levels can be
nested, but if there are more than three, they can become difficult to read.
if (Boolean condition 1)
if(Boolean condition 2)
Statement 1;
else
Statement 2;
else
Statement 3;
Statement3 Boolean
True False
Condition2
Statement1 Statement2
if (Boolean condition 1)
if(Boolean condition 2)
Statement 1;
else /* dangling else */
Statement 2;
The following code is the solution to the dangling else problem.
if (Boolean condition 1)
{
if(Boolean condition 2)
Statement 1;
}
else /* dangling else */
Statement 2;
if (Boolean condition)
Statement ;
else if (Boolean condition)
Statement ;
else if (Boolean condition)
Statement ;
else if (Boolean condition)
Statement ;
else
Statement ;
#include <stdio.h>
main ( )
{
int x;
printf("Enter an integer between 1 and 6");
scanf(―%d‖,&x);
if(x==1)
printf("The number is one \n");
else if(x==2)
printf("The number is two \n");
else if(x==3)
printf("The number is three\n");
else if(x==4)
printf("The number is four \n");
else if(x==5)
printf("The number is five \n");
else if(x==6)
printf("The number is six \n");
else
printf("You didn't follow the rules");
}
Multi-way Selection:
In addition to two-way selection, most programming languages provide another selection
concept known as multi-way selection.
Switch statement:
The C switch allows multiple choice of a selection of items at one level of a conditional where it
is a far neater way of writing multiple if statements:
This is another form of the multi way decision. It is well structured, but can only be used in certain
cases where;
Only one variable is tested, all branches must depend on the value of that variable. The
variable must be an integral type. (int, long, short or char).
Each possible value of the variable can control a single branch. A final, catch all, default
branch may optionally be used to trap all unspecified cases.
A switch statement is a conditional statement that tests a value against different values. If the
value is matched, the corresponding group of statements is executed. A switch statement begins
with the switch keyword that is followed by a value expression in the parenthesis ( ). It is a
combination of multiple case labels that must be separated by the break statement. Every case
label contains a constant value that is matched against the value, which is specified in the
switch (expression) {
case item1:
statement1;
break;
case item2:
statement2;
break;
case itemn:
case itemn statementn;
break;
default:
statement;
break;
}
In each case the value of itemi must be a constant, variables are not allowed. Floating point
constants are not allowed to represent case value.
The break is needed if you want to terminate the switch after execution of one choice.
Otherwise the next case would get evaluated.
{
case `A':
case `E':
case `I':
case `O':
case `U':
numberofvowels++;
break;
case ‘ ':
numberofspaces++;
break;
default:
numberofconsonants++;
break;
}
Multi-way
Expression
The term iteration means repetitive execution of the same set of instructions for a given
number of times or until a specified result is obtained. The statements that are executed repetitively
are called as iterative statements. Iterative statements are also popularly known as loop constructs,
which repeatedly execute a block of code based on a condition expression, as long as the condition
evaluates to true. The loop exits when the conditional expression evaluates to false. After that, the
control transferred to the next statement that follows the loop. The following are the iterative
statements supported by C:
Loop statement in C:
The while loop keeps repeating an action until an associated test returns false. This is
useful where the programmer does not know in advance how many times the loop will be
traversed.
The do while loops is similar, but the test occurs after the loop body is executed. This
ensures that the loop body is run at least once.
The for loop is frequently used, usually where the loop will be traversed a fixed number
of times. It is very flexible, and novice programmers should take care not to abuse the
power it offers.
while statement:
We use a while statement to continually execute a block of statements while a condition remains
true. The following is the general syntax of the while statement.
while (expression)
{
Statement 1;
Statement 2;
:
Statement n;
}
First, the while statement evaluates expression, which must return a Boolean value. If the
expression returns true, the while statement executes the statement(s) in the while block. The
while statement continues testing the expression and executing its block until the expression
returns false. In while loop, first conditional expression is evaluated and then statements are
executed if the expression returns true. Therefore while loop is also called as entry condition loop.
#include <stdio.h>
main()
{
int fact=1, i=1,n;
printf(―input a number\n‖);
scanf(―%d‖,&n);
if(n==0)
fact=1;
else
Loop False
Condition
True
Statements
do –while statement:
Each line of a C program up to the semicolon is called a statement. The semicolon is the statement's
terminator. The braces { and } which have appeared at the beginning and end of our program unit
can also be used to group together related declarations and statements into a compound statement
or a block.
In the case of the while loop before the compound statement is carried out the condition is
checked, and if it is true the statement is obeyed one more time. If the condition turns out to be
false, the looping isn't obeyed and the program moves on to the next statement. So we can see that
the instruction really means while something or other is true keep on doing the statement.
In the case of the do while loop it will always execute the code within the loop at least once, since
the condition controlling the loop is tested at the bottom of the loop. The do while loop repeats
the instruction while the condition is true. If the condition turns out to be false, the looping isn't
obeyed and the program moves on to the next statement. Therefore, do-while loop is also called as
exit-condition loop.
Loop
True Condition
False
for statement:
The for statement provides a compact way to iterate over a range of values. The general
form of the for statement can be expressed as follows.
Statement 1;
Statement 2;
:
Statement n;
}
The initialization expression initializes the loop — it's executed once at the beginning of the loop.
The loop_condition determines when to terminate the loop. When the expression evaluates to
false, the loop terminates. Finally, loop_progress_expression is an expression that gets invoked
after each iteration through the loop. All these components are optional. In fact, to write an infinite
loop, you omit all three expressions.
for ( ; ; ) { //infinite loop
...
}
Let us consider an example to calculate the factorial of a number using the for loop.
#include <stdio.h>
main()
{
If we use a comma expression for the second expression in a for loop, make sure that the loop
control is the last expression.
Nested Loop:
The loop can be nested (i.e. embedded) one within another is called nested loop. The same
type of control structure need not generate the inner loop and outer loop. It is essential, however,
break;
The break statement can be used in any of the loop statements- while, for and do-while and
in the selection switch statement. The following example illustrates the use of break statement in
a loop.
#include<stdio.h>
main( )
{
In the above program, the variable i is initialized with zero value and the while loop is used to
display even numbers from 2 to infinity. However, the program displays even numbers up to 10.
This is because, an if statement checks whether the number stored in the variable i is greater than
10; and if it is greater than 10, the while loop is terminated by the break statement.
continue statement:
The break statement breaks the entire loop, but a continue statement breaks the current
iteration. In other words, the continue statement breaks the current execution of a loop condition
and then continue the loop with next condition. However, the break statement breaks the entire
loop when a specified condition of the loop is met. Note the continue statement also needs a
semicolon. The syntax of the continue statement is as follows:
continue;
Output:
2
4
8
In the above program, first 10 even numbers are printed excluding 6 and 14. This is done with the
help of the continue statement inside an if condition, which gets executed in case the value of I
variable becomes either 6 or 14. In the output of the above program, even numbers are shown
successfully until the value of i becomes 6 or 14. When the value of i becomes 6, the control of
execution quits from the current loop and returns back to the for loop. The next iteration then
displays the remaining even numbers till the value of i becomes 14. Then, the control of execution
again quits the current loop and returns back to the for loop. The next iteration displays the
remaining even numbers.
Unconditional Control Statement- goto Statement:
The goto statement is used to perform a transfer of control from one statement to another
in a program. This statement uses user-defined labels to specify the goto statement in the program.
The syntax to use the goto statement is
goto label_name;
………….
………….
label_name: Statement;
In the preceding syntax, label_name specifies a user-defined label for the target statement
to which the control should be transferred. This label should be followed by a colon and the target
statement must be preceded by the label.
goto statement is not allowed in structured programming.