C Programming Unit 2 Part - 1 Notes - Operators and Conditional Statements
C Programming Unit 2 Part - 1 Notes - Operators and Conditional Statements
STATEMENTS (LOOPS)
Operators and Expressions
An operator is a symbol or a token that specifies the operation to be performed on various types of
data. Ex: +, -, *.
An expression is a sequence of operands and operators that reduces to single value. Eg: a+b-c*a/2
OPERAND is a constant or a variable which returns a value. An operator may have one or two, three
operands.
1. Unary operators: An operator which acts on only one operand to produce the result. Eg: -10, -a, *b,
a++ etc.
2. Binary operators: An operator which acts on two operands to produce the result. Eg: a+b, a*b.
3. Ternary operators: An operator which acts on three operands to produce a result. Eg: a?b:c
1. Arithmetic operators:
Arithmetic operators are used to perform mathematical calculations like addition, subtraction,
multiplication, division and modulus in programs.
Arithmetic operators:
Operator Description Precedence Associativity Example
+ Addition or unary plus 2 L->R A+B
_ Subtraction or unary minus 2 L->R A-B
* Multiplication 1 L->R A*B
/ Division 1 L->R A/B
% Modulo division 1 L->R A%B
1
ARITHMETIC OPERATOR’S PRECEEDENCE / precedence of operators:
The order in which different operators are used to evaluate an expression is called precedence of
operators or hierarchy of operators. Operators are evaluated from Highest to lowest. When two or more
operators have the same precedence, then precedence rules are not applicable. 2 types of operator
associativity are:
1. Left to right associativity: in an expression, when two or more operators have the same precedence/
Priority, then it is evaluated from left to right.
2. Right to Left associativity: in an expression, When two or more operators have the same
precedence/ Priority, and if we evaluated from right to left then it is called Right to Left
associativity.
BODMAS rule:
Highest to lowest:
2 TYPE CONVERSION:
In C language, a programmer can instruct the compiler to convert the data from one data type to another
data type. This process is called type conversion.
1. Implicit conversion. Process of converting data types from lower rank to higher rank is done
automatically by C compiler is called implicit conversion or promotion ( int to float) . Eg: 1 /2.0
gets converted to 1.0/2.0
2. Explicit conversion: Process of converting data types from higher rank to lower rank or converting
same data type to other data type is done manually called explicit conversion. Here forcible
conversion is done from one data type to another data type or promotion (float to int) Eg: 1/(float)2
gets converted to 1.0/2.0.
#include<stdio.h>
int main()
{
int a,b,add,sub,mul,mod;
float div;
printf(“enter the values of a and b\n”);
scanf(“%d%d”, &a,&b);
add = a+b;
sub = a-b;
mul = a*b;
div = (float)a/b;
mod = a%b;
2
printf(“ Modulus of a and b is: %d\n”,mod);
return 0; }
Output:
Addition of a and b is: 60
Subtraction of a and b is: 20
Multiplication of a and b is: 800
Division of a and b is: 2.000000
Modulus of a and b is: 0
3 Relational Operators:
A relational operator, also known as a comparison operator, is one that compares two values.
Operators that are used to find the relationship between two operands are called relational operators.
Expressions that contain relational operators are called relational expressions. It takes the following form:
if(a>b)
printf(“ a is larger\n”);
else
printf(“ b is larger\n”);
return 0;
}
4. Logical Operators: In addition to the relational operators, C has the following three logical operators.
These operators are used to combine 2 or more relational expressions.
3
Operator Decryption Precedence Associativity
&& Logical AND 2 L->R
|| Logical OR 3 L->R
! Logical NOT 1 L->R
Examples:
If (a > b && x == 10), if (age > 55 && salary < 1000), if (number < 0 || number >100)
! (Negation) :It takes only one operand return a false value if the operand is true and vice versa.
&&(logical AND): Operator combines logical expressions in such a way that the resultant
expression gives true only if both the expressions are true. In any other condition it gives false.
| | (logical OR): If either one of the expression is true, it gives true.
R1 R2 R1 && R2 R1 || R2 ! R1
For example, Let’s take 3 variables a = 10, b = 5, c = 0 and here are some logical AND operations:
For example, Let’s take 4 variables a =10, b = 5, c = 0, d = 0 and here are some logical OR operations:
For example: Let’s take 3 variables a=10, b=5, c =0, d= -6 and here are some logical NOT operations:
NOT OPERRATION Expression Result
!(a == 10) !1 0
!(b>a) !0 1
!c !0 1
4
Example program to demonstrate logical operators.
if(a>b || a>c)
printf(“ a is larger\n”);
else if (b>a || b>c)
printf(“ b is larger\n”);
else
printf(“ c is larger\n”);
return 0;
}
5. ASSIGNMENT OPERATORS:
An operator which is used to assign the data or result of an expression into a variable (also called
memory location) is called an assignment operator. It is denoted by ‘=’ sign. A statement with assignment
operator is called assignment statement or assignment expression.
The operand on the left hand side must be a variable, while the operand on the right hand side can
be any variable, constant or expression.
x=8 8 is assigned to x
y=5 5 is assigned to y
S=x+y Value of an expression x + y is assigned to s
x=y=4 4 is assigned to both x and y(Multiple assignment operator)
Three types:
5
Example:
max = (a > b)?a : b; //compute maximum of a and b
Here, whenever the condition a greater then b is true, the value of ‘a’ is assigned to max. Otherwise, the
value of ‘b’ is assigned to max.
/* Program to find largest of two numbers using ternary operator */
#include <stdio.h>
int main()
{
int a=7, b=8, big;
big=(a>b)?a:b;
printf(“%d”, big);
return 0;
}
output: 8
6
Example:
Post increment Pre increment
Program-1: Tracing: Program-1: Tracing:
a++; a = 21 ++a; a = 21
Output: Output:
printf(“%d”, a); 21 printf(“%d”, a); 21
} }
b = a++; b = 20 b = ++a; b = 21
/* b = a */ a = 21 /* a = a + 1 */ a =21
/* a = a + 1 */ Output: /* b = a */ Output:
printf(“%d”, a); 21 printf(“%d”, a); 21
printf(“%d”, b); 20 printf(“%d”, b); 21
} }
In program 1: there is no change in output. i.e both the pre increment and post increment are same.
But it will change in expression. In case of pre increment the value of ‘a’ is incremented and then it is
assigned to ‘b’. But in case of post increment the value of ‘a’ is assigned to ‘b’ and then value of gets
incremented (In program 2).
Note: b = a++ b = a; b = ++a a = a + 1;
a = a+1; b = a;
Decrement operator (--): is a decrement operator. It decrements the value of a variable by one. The
decrement operators are classified into two categories.
7
Example
8
Bitwise AND (&): If the corresponding bit position in both operands are 1, then AND operation
results in 1: otherwise, AND operation results in 0. The bitwise AND operator is denoted by the
symbol ‘&’. The bitwise AND operations on to bits are shown below.
0&0=0 1&0=0
0&1=0 1&1=1
Bitwise OR (|):If the corresponding bit position in both operands are 0, then OR operation results
in 0: otherwise, OR operation results in 1. The bitwise OR operator is denoted by the symbol ‘|’. The
bitwise OR operations on to bits are shown below.
0|0=0 1|0=1
0|1=1 1|1=1
Bitwise XOR (^):If the corresponding bit position in both operands are different, then XOR
operation results in 1: otherwise, XOR operation results in 0. The bitwise XOR operator is denoted
by the symbol ‘^’. The bitwise XOR operations on to bits are shown below.
0^0=0 1^0=1
0^1=1 1^1=0
Left shift operator (<<): The operator that is used to shift the data by a specified number of bit
positions towards left is called left shift operator. In C language, left shift operator is denoted by the
symbol <<. The syntax is shown below:
Syntax:
b = a << num;
where
The first operand is the value to be shifted.
The second operand specifies the number of bits to be shifted.
The contents of first operand are shifted towards left by the number of bit positions specifies in second
operand.
Example: b = 5 << 1;
the data 5 is shifted left by 1 bit-position as shown below and the result is stored in the variable b.
Discard MSB bit
0 0 0 0 0 1 0 1
Right shift operator (>>): The operator that is used to shift the data by a specified number of bit
positions towards right is called right shift operator. In C language, right shift operator is denoted by
the symbol >>. The syntax is shown below:
Syntax:
b = a >> num;
where
The first operand is the value to be shifted.
The second operand specifies the number of bits to be shifted.
9
The contents of first operand are shifted towards right by the number of bit positions specifies in second
operand.
Example: b = 5 >>1;
The data 5 is shifted right by 1 bit-position as shown below and the result is stored in the variable b.
LSB is discarded
0 0 0 0 0 1 0 1
Bitwise Negate /One’s complement (~): The operator that is used to change every bit from 0 to 1
and 1 to 0. And denoted by the symbol ~ (tilde).
Eg:
#include <stdio.h>
int main()
{
int a=10;
int b=~a;
return 0;
}
Here, a=10 i.e in binary representation 8 bits: 00001010
Its compliment is 11110101 i.e 245 in decimal which is assigned to b.
9.Special Operators:
The sizeof Operator: The sizeof is a compile time operator and, when used with an operand, it
returns the number of bytes the operand occupies. The operand may be a variable, a constant or a
data type qualifier.
Example: m = sizeof(sum);
n = sizeof(long int);
k = sizeof(235L);
The sizeof operator is normally used to determine the lengths of arrays and structures when
their sizes are not known to the programmer.
It is also used to allocate memory space dynamically to variables during execution of a
program.
10
Operator Precedence and Associativity:
Operator Description Associativity Preced
ence
() Function call Left to right 1
[] Array element reference
+ Unary plus Right to left 2
- Unary minus
++ Increment
-- Decrement
! Logical negation
~ Ones complement
* Pointer reference
& Address
sizeof Size of an object
(type) Type cast(conversion)
* Multiplication Left to right 3
/ Division
% Modulus
+ Addition Left to right 4
- Subtraction
<< Left shift Left to right 5
>> Right shift
< Less than Left to right 6
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equality Left to right 7
!= Inequality
& Bitwise AND Left to right 8
^ Bitwise XOR Left to right 9
| Bitwise OR Left to right 10
&& Logical AND Left to right 11
|| Logical OR Left to right 12
?: Conditional operators Left to right 13
= Assignment operators Right to left 14
+= ,-= ,*= ,/= ,%=
<<=,>>=, &=, |=, ^=
, Comma operator Left to right 15
Evaluation of Expressions:
Rules for Evaluation of Expression:
First, parenthesized sub expression from left to right is evaluated.
If parentheses are nested, the evaluation begins with the innermost sub-expression.
The precedence rule is applied in determining the order of application of operators in evaluating sub-
expressions.
The associativity rule is applied when two or more operators of the same precedence level appear in
a sub-expression.
11
Arithmetic expressions are evaluated from left to right using the rules of precedence.
When parentheses are used, the expressions within parentheses assume highest priority.
12
13
14
15
Based on assignment operator
16
Based on Increment and Dec operator
17
18
19
2.3 BRANCHING CONSTRUCTS
In a 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 true. And other set of
statements may have to be skipped during execution when other condition are true.
The statements that transfer the control from one place to other place in the program with condition
are called branching or condition statements. These statements alter the sequence of instructions.
2 types of conditional statements are:
1. Conditional branch statements
2. Un-conditional branch statements
2. Jumping statements: Also called unconditional statements. Used to jump from one part of program
to another part. There are several types of jumping statements:
break statements
continue statements
goto statements
return statements
20
1. if statement
Statements x
It has two paths true (1) or false (0).
First, the test exp is evaluated. If test exp is true, statements of if block (statements 1 to n) are
executed. If false, these statements will be skipped and statement “x” will be executed.
21
Examples:
1. Program to check for even number.
2. Program to find the largest of 2 numbers
2.If-else statement
Syntax: True False
Test
if(test expression) exp
{
true block statements;
}
else True block False block
{ Statements Statements
false block statements;
}
Statement x;
Statements x
This feature permits the programmer to write a single comparison, and then execute one of the two
statements depending upon whether the test expression is true or false. It is two way selection statement.
Here also expression in parentheses must evaluate to true or false. Typically you're testing something
to see if it's true, and then running a code block (one or more statements) if it is true, and another block of
code if it isn't. The statement1 or statement2 can be either simple or compound statement.
22
Examples:
1. Program to check for leap year.
2. Program to find the largest of 2 numbers
3. Nested if statements
An if statements within another if statements are called nested if statements.
if (Test expression1)
{
if(Test expression2)
Block a;
else
Block b;
}
else
{
Block c;
}
In this, expression1 is evaluated first. If it returns true then it will evaluate the expresssion2. if expression2
is true then it will execute block a. if it returns false then it will returns block b. If expression1 is false then
it will returns block c.
23
4.if-else-if statement / if-else ladder
It works in the same way as a simple if statement. Used to test additional conditions apart from the initial
test expression. You can set up an if-else statement to test for multiple conditions. The following example
uses two conditions so that if the first test fails, we want to perform a second test before deciding what to
do:
} Statements Statements
else Block 2 Block n
{
Statement block n;
}
Statement x;
Statements x
The various conditions are evaluated one by one starting from top to bottom, on reaching a condition
evaluating to true the statement group associated with it are executed and skip other statements. If none of
expression is evaluate to true, then the statement or group of statement associated with the final else is
executed.
Examples:
1. Program to find the largest of 3 numbers
2. Implement a Program to display the grade of a student based on the marks obtained.
3. Implement a Program to read the nonzero coefficients of a quadratic equation and
compute and display its roots.
24
5.Switch statement
The switch statement is a control statement used to make a selection between many alternatives.
Here choice value can be integer or character data type. Switch statements simulate the use of multiple if
statement. Syntax of c switch statement is:
switch (expression)
{
case value1:
statements 1;
break;
case value2:
statements 2;
break;
.
.
.
.
case value n:
statements n;
break;
default:
statements n;
}
When the switch statement is executed, the expression in the switch statement is evaluated and
the control is transferred directly to the group of statements whose case value matches the value of the
expression. Each group of statement ends with a break statement. The execution of break statement causes
immediate exit from the switch statement. If break statement is not present, then the execution will falls
through all the statement in the selected case. If none of the case-label value matches the value of
expression, then control comes out of the switch statements and is transferred directly to the statement that
follows the switch statement.
25
The expression that forms the argument of switch is evaluated to either char or integer. Similarly the
constant expression follows the keyword case should be a value int or char. That is, names of variable can
also be used. Switch can test for only equality. It’s illegal to have more than one case label using the same
value.
#include <stdio.h>
int main()
{
char op;
float num1, num2;
printf("Enter operator either + or - or * or divide : ");
scanf("%c", &op);
printf("Enter two operands: ");
scanf("%f%f", &num1, &num2);
switch(op)
{
case '+': printf("%f + %f = %f",num1, num2, num1+num2); break;
case '-': printf("%f - %f = %f",num1, num2, num1-num2); break;
case '*': printf("%f * %f = %f",num1, num2, num1*num2); break;
case ‘/’: if(num2==0)
printf(“Division Not Possible”);
else
printf(“%f * %f = %f",num1, num2, num1/num2);
break;
default: printf(“Invalid Operator”);
}
26
return 0;
}
27
UNCONDITIONAL BRANCHING STATEMENTS / Jumps in Loops
1.BREAK:
Break statement is jump statement which can be used in switch and looping statements.
The break statement in switch statement causes control to terminate switch statements and
statements following switch statement will be executed. Break statement will be the last statement.
If Break statement is used in loops (for, while, do while), the control comes out of the loop and the
statements following the loop will be executed. It is used to terminate the loop when a specific
condition is reached.
Syntax: Break;
If break statement appears in the inner loops of a nested loop, then control will comes out of the
inner loop.
Example:;
main()
{
int i;
for(i=0;i<=5;i++)
{
if(i==4)
break;
printf(“%d”,i);
}
}
Output: 0 1 2 3
28
2. CONTINUE STATEMENTS
During execution of a loop, it may be necessary to skip a part of the loop based on some conditions.
In such cases, we use continue statement. The continue statement is used only in the loops to terminate the
current iteration.
Ex: during processing of student records, it may be necessary to exclude student names whose marks
are less than or equal 50. In such case, in a program we need to check the marks whether it is less than or
equal to 50. In such case program has to skip such student details by using continue statement.
Example:
main()
{
Int i;
for(i=0;i<=5;i++)
{
if(i==4)
continue;
printf(“%d”,i);
}}
Output: 0 1 2 3 5
3.GOTO STATEMENT:
It is a jump statements that transfers the control to the specified statement in a program. i.e Used to
transfer control to a specified label.
Label: is an identifier that specifies the place where the branch is to be made. Label can be any valid
variable name followed by a colon (:).
Whenever the goto statement is encountered, the control is immediately transferred to statements
following label.
Goto statement is often combined with if statements.
29
Label:
.
.
Syntax: .
.
.
goto label;
-------- Statements;
-------- --------
--------
Label:
Goto label
Statements;
30