1. C Operators and Control
Structures
Dr.Mary Jacob
Kristu Jayanti College(Autonomous)
Bangalore
2. Operators in C
An operator is a symbol that tells the compiler to perform a certain
mathematical or logical manipulation. Operators are used in programs to
manipulate data and variables.
C operators can be classified into following types based on the operation it
does:
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Bitwise operators
5. Assignment operators
6. Conditional operators
7. Special operators
3. Classification is based on the number of operands
Operators that work on single operand
Example:
increment operator( ++) or the decrement operator( - - ).
int a =b++; or something like int C =d- -;
Operators that operate on two operands
Example:
‘+’, ‘ -’, ‘ *’, ‘/’. Syntax can be like int C=a+b;
Operators that operates on three operands. It takes three argumets .
1st argument is checked for its validity . If it is true 2nd argument is returned else third
argument is returned.
Example:
int large= num1>num2 ? num1:num2;
In this example if num1 is greater than num2 'num1' is assigned to large otherwise 'num2' is assigned.
5. Arithmetic Operators-Example
/* Program to Perform Arithmetic Operations in C */
#include<stdio.h>
void main()
{
int a = 12, b = 3;
int addition, subtraction, multiplication, division, modulus;
addition = a + b;
subtraction = a - b;
multiplication = a * b;
division = a / b;
modulus = a % b;
printf("Addition of two numbers a, b is : %dn", addition);
printf("Subtraction of two numbers a, b is : %dn", subtraction);
printf("Multiplication of two numbers a, b is : %dn", multiplication);
printf("Division of two numbers a, b is : %dn", division);
printf("Modulus of two numbers a, b is : %dn", modulus);
}
7. Relational Operators-Example
// Working of relational operators #include <stdio.h>
void main()
{
int a = 5, b = 5, c = 10;
printf("%d == %d is %d n", a, b, a == b);
printf("%d == %d is %d n", a, c, a == c);
printf("%d > %d is %d n", a, b, a > b);
printf("%d > %d is %d n", a, c, a > c);
printf("%d < %d is %d n", a, b, a < b);
printf("%d < %d is %d n", a, c, a < c);
printf("%d != %d is %d n", a, b, a != b);
printf("%d != %d is %d n", a, c, a != c);
printf("%d >= %d is %d n", a, b, a >= b);
printf("%d >= %d is %d n", a, c, a >= c);
printf("%d <= %d is %d n", a, b, a <= b);
printf("%d <= %d is %d n", a, c, a <= c);
}
8. Logical Operators in C
Ø The logical
operator returns
either 0 or 1
depending upon
whether
expression results
true or false.
Ø Logical operators
are commonly
used in decision
making in C
programming.
9. Logical Operators in C
// Working of logical operators #include <stdio.h>
void main()
{
int a = 5, b = 5, c = 10, result;
result = (a == b) && (c > b);
printf("(a == b) && (c > b) is %d n", result);
result = (a == b) && (c < b);
printf("(a == b) && (c < b) is %d n", result);
result = (a == b) || (c < b);
printf("(a == b) || (c < b) is %d n", result);
result = (a != b) || (c < b);
printf("(a != b) || (c < b) is %d n", result);
result = !(a != b);
printf("!(a == b) is %d n", result);
result = !(a == b);
printf("!(a == b) is %d n", result);
10. Assignment Operators in C
Ø Assignment Operator is
used to assign value to an
variable and is denoted
by equal to sign.
Ø It is a binary operator
which operates on two
operands.
Ø It has two Values : L-Value
and R-Value .
Ø copies R-Value into L-
Value.
11. Assignment Operators in C
// Working of assignment operators
#include <stdio.h>
void main()
{
int a = 5, c;
c = a; // c is 5
printf("c = %dn", c);
c += a; // c is updated to 10
printf("c = %dn", c);
c -= a; // c changes to 5
printf("c = %dn", c);
c *= a; // c is updated to 25
printf("c = %dn", c);
c /= a; // c is updated to 5
printf("c = %dn", c);
c %= a; // Now c = 0
printf("c = %dn", c);
12. Bitwise Operators in C
Ø The mathematical operations like addition,
subtraction, multiplication, division etc. are
converted to bit-level to make processing faster
and save power.
Ø Bitwise operator works on bits and performs
bit by bit operation.
13. Bitwise AND
Bitwise AND
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bit Operation of 12 and 25
00001100
&00011001
00001000 = 8 (In decimal)
14. Bitwise OR
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bitwise OR Operation of 12 and 25
00001100
|00011001
00011101 = 29 (In decimal)
15. Bitwise XOR
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bitwise XOR Operation of 12 and 25
00001100
^00011001
00010101 = 21 (In decimal)
16. Bitwise NOT
Bitwise Complement Operator
35 = 00100011 (In Binary)
Bitwise complement Operation of 35
~ 00100011
11011100 = 220 (In decimal)
17. Bitwise AND,OR,XOR,NOT-Example
//Working of Bitwise AND,OR,XOR,Compliment
#include <stdio.h>
void main()
{
int a = 12, b = 25;
printf("AND Output = %d", a&b);
printf("OR Output = %d", a|b);
printf("XOR Output = %d", a^b);
printf("Complement Output = %dn",~35);
}
18. Shift Operators
There are two shift operators in C:Right Shift and Left Shift
Right shift operator - shifts all bits to right by certain number of specified bits
specified by >>.
Example:
212 = 11010100 (In binary)
212>>2 = 00110101 (In binary) [Right shift by two bits]
19. Shift Operators
Left shift operator - shifts all bits to left by certain number of specified bits specified by
<<.
Example:
212 = 11010100 (In binary)
212<<1 = 01010000 (In binary) [Left shift by two bits]
20. Shift Operators-Example
//Working of shift Operators
#include <stdio.h>
void main()
{
int num=212, i;
for (i=0; i<=2; ++i)
printf("Right shift by %d: %dn", i, num>>i);
printf("n");
for (i=0; i<=2; ++i)
printf("Left shift by %d: %dn", i, num<<i);
}
21. Increment Operators
Increment operator is used to increment the current value of variable by adding integer 1
and can be applied to only variables denoted by ++.
Two types of increment operator
Pre-Increment Operator - is used to increment the value of variable before using in the
expression
Example: a=5; b = ++a;
The value of b will be 6 because 'a' is incremented first and then assigned to 'b'.value of
'a' is 6
Post-Increment Operator - is used to increment the value of variable after executing
expression in which post increment is used.
Example: a=5; b = a++;
The value of b will be 5 because 'b' is assigned first and then .value of 'a' is incremented
to 6
23. Decrement Operators
Decrement operator is used to decrease the current value of variable by subtracting
integer 1 and can be applied to only variables and is denoted by --.
Pre-decrement operator :It is used to decrement the value of variable before using in
the expression.
Example: a=10; b=--a;
Value of 'b' will be 9 and 'a' will also be 9.
Post-decrement Operator : In this the old value is first used in a expression and then old
value will be decrement by 1.
Example: a=10; b=a--;
Value of 'b' will be 10 and 'a' will be 9.
25. Conditional Operator
The? : Operator
The conditional operator ? : can be used to replace if...else statements. It has the
following general form:
Exp1 ? Exp2 : Exp3;
where Exp1, Exp2, and Exp3 are expressions.
The value of a ? expression is determined like this: Exp1 is evaluated. If it is true, then
Exp2 is evaluated and becomes the value of the entire ? expression. If Exp1 is false, then
Exp3 is evaluated and its value becomes the value of the expression.
This is also called as Ternary Operator because it uses three operands.
26. Conditional Operator-Example
//Program to check if a number is odd or even
#include<stdio.h>
int main()
{
int num;
printf("Enter the Number : ");
scanf("%d",&num);
(num%2==0)?printf("Even"):printf("Odd");
}
27. Miscellaneous Operators
There are few other important operators in C. They are:
sizeof()
Returns the size of an variable.
sizeof(a), where a is integer, will return 2.
&
Returns the address of an variable.
&a; will give actual address of the variable.
*
Pointer to a variable.
*a; will pointer to a variable.
,
Comma Operator
separate the declaration of multiple variables.
28. TYPE CONVERSIONS
Converting one datatype into another is known as type casting or, type-conversion.
Toconvert the values from one type to another explicitly the cast operator is used:
Syntax: (datatype) expression
C can perform conversions between different data types. There are two types of
type conversions.
Implicit type conversion
Explicit type conversion
29. TYPE CONVERSIONS
Implicit type conversion
When we perform arithmetic manipulation on operands belonging to different data
types, they may undergo type conversion automatically before evaluating the final
value. This conversion performed by the compiler without programmer's
intervention.
Explicit conversion (Type Casting)
An explicit type conversion is user-defined that forces an expression to be of
specific type. Variables may be converted explicitly by type casting.
The general form is
(data_type) expression;
Where data_type is any allowed data type like int, char, float or double, and
expression includes constant, variable or expression.
30. TYPE CONVERSIONS
Integer promotion
It is the process by which values of
integer type " smaller" than int or
unsigned int are converted either to int or
unsigned int.
Arithmetic Conversion
The usual arithmetic conversions are
implicitly carried out to cast their values
to a common type. The compiler first
performs integer promotion and if the
operands still have different types, then
they are converted to the data type that
appears highest in the hierarchy as below
31. PRECEDENCE
Operator precedence determines the grouping of terms in an expression. This affects
how an expression is evaluated. Certain operators have higher precedence (priority)
than others.
For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher
precedence than + so it first get multiplied with 3*2 and then adds into 7.
Here operators with the highest precedence appear at the top of the table and those
with the lowest appear at the bottom. Within an expression, higher precedence
operators will be evaluated first.
32. ASSOCIATIVITY
The associativity determines the direction in which an expression is
evaluated.
Example:
1 == 2 != 3 ,the associativity is from left to right
a =b , associativity is from right to left
34. Decision Making Statements
Decision making structures
allows the programmer to
s p e c i f y o n e o r m o r e
conditions to be evaluated or
tested by the program, along
w i t h a s t a t e m e n t o r
statements to be executed if
the condition is determined to
be true, and optionally, other
statements to be executed if
the condition is determined to
be false.
35. if statement
if statement is a one-way branching in which the statements will only execute if the given
expression is true.An if statement consists of a Boolean expression followed by one or more
statements.
Syntax:
if(condition)
{
/* statement(s) will execute if the boolean expression is true */
}
If the boolean expression evaluates to true then the block of code inside the if statement
will be executed. If boolean expression evaluates to false then the first set of code after the
end of the if statement (after the closing curly brace) will be executed.
38. if else statement
if-else statement is used if we want to execute some code if the
condition is true and another code if the condition is false.An if
statement can be followed by an optional else statement, which
executes when the boolean expression is false.
Syntax:
if(condition)
{
/* statement(s) will execute if the boolean expression is true */
}
else
{
/* statement(s) will execute if the boolean expression is false */
}
39. if else statement
if-else statement is used if we want to execute some code if the
condition is true and another code if the condition is false.An if
statement can be followed by an optional else statement, which
executes when the boolean expression is false.
Syntax:
if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}
else
{
/* statement(s) will execute if the boolean expression is false */
}
40. Nested if statement
A nested if statement is an if statement placed inside another if statement. Nested if statements are often used when you must test a
combination of conditions before deciding on the proper action. ie.)You can use one if or else if statement inside another if or else if
statement(s).
Syntax:
if ( test condition 1)
{
//If the test condition 1 is TRUE then these it will check for test condition 2
if ( test condition 2)
{
//If the test condition 2 is TRUE then these statements will be executed
Test condition 2 True statements;
}
else
{
//If the test condition 2 is FALSE then these statements will be executed
Test condition 2 False statements;
}
else
{
//If the test condition 1 is FALSE then these statements will be executed
Test condition 1 False statements;
}
42. else if ladder/if else ladder
if-else ladder is an extension of if…else statement. By
using one if-else construct, it is possible to choose
between two choices. There may be a situation
wherein it is required to select one among more than
two choices. This can be accomplished by another if-
else in the else part of the construct. This type of if
construct is called as else if ladder statement.
45. Switch Statement
A switch statement allows a variable to be tested against several values
for equality. Each of these values is called a case. Once a matching case
is found, its particular block of code is executed. It is an alternative to
the more common if-else statement.
47. Switch
The following rules apply to a switch statement:
The expression used in a switch statement must have an int,char or enumerated type.
There can be any number of case statements within a switch. Each case is followed by the value
to be compared to and a colon.
The constant-expression for a case must be the same data type as the variable in the switch, and
it must be a constant or a literal.
When the variable being switched on is equal to a case, the statements following that case will
execute until a break statement is reached.
When a break statement is reached, the switch terminates, and the flow of control jumps to the
next line following the switch statement.
Not every case needs to contain a break. If no break appears, the flow of control will fall through
to subsequent cases until a break is reached.
A switch statement can have an optional default case, which must appear at the end of the
switch. The default case can be used for performing a task when none of the cases is true. No
break is needed in the default case.
48.
49. Looping Statements
There may be a situation when you
need to execute a block of code
several number of times. A loop
statement allows us to execute a
statement or group of statements
multiple times and following is the
general from of a loop statement:
50. while Loop
While loop is also known as a pre-tested loop.In general, a while loop allows a part of the code
to be executed multiple times depending upon a given boolean condition. It can be viewed as
a repeating if statement. The while loop is mostly used in the case where the number of
iterations is not known in advance.A while loop statement in C repeatedly executes a target
statement as long as a given condition is true. entry controlled loop/pre tested loop
Syntax:
while(condition)
{
statement(s);
}
51. while Loop
The statement(s) may be a single statement or a block of statements. The condition may be
any expression. The loop repeats while the condition is true.When the condition becomes
false, program control passes to the line immediately following the loop.
ØThe conditional expression is used to check the condition. The statements
defined inside the while loop will repeatedly execute until the given condition
fails.
ØThe condition will be true if it returns 0. The condition will be false if it returns
any non-zero number.
ØIn while loop, the condition expression is compulsory.
ØRunning a while loop without a body is possible.
ØWe can have more than one conditional expression in while loop.
ØIf the loop body contains only one statement, then the braces are optional.
53. do...while loop
The do..while loop is similar to the while loop with one important difference. The body of
do...while loop is executed at least once. Only then, the test expression is evaluated.The
do...while loop checks its condition at the bottom of the loop. A do...while loop is an exit
controlled loop. The body of the loop gets executed at least one time irrespective of the
condition evaluated. Therefore the minimum number of execution of do…while loop is one.
exit controlled loop/post tested loop
Syntax:
do
{
statement(s);
}while(condition);
54. do...while loop
The conditional expression appears at the end of the loop, so the statement(s) in the loop
execute once before the condition is tested.If the condition is true, the flow of control jumps
back up to do, and the statement(s) in the loop execute again. This process repeats until the
given condition becomes false.
ØThe body of do...while loop is executed once. Only then, the test expression is evaluated.
Ø If the test expression is true, the body of the loop is executed again and the test expression
is evaluated.
Ø This process goes on until the test expression becomes false.
Ø If the test expression is false, the loop ends.
56. for loop
A for loop is a repetition control structure that allows to efficiently write a loop that
needs to execute a specific number of times.
Syntax:
for(initialization;condition;increment/decrement)
{
statement(s);
}
57. for loop
The flow of control in a for loop is:
1.The initialization step is executed first, and only once. This step allows to declare and initialize
loop control variables. It is not required to put a statement here, as long as a semicolon appears.
2.Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the
body of the loop does not execute and flow of control jumps to the next statement just after
the for loop.
3.After the body of the for loop executes, the flow of control jumps back up to the increment
statement. This statement allows you to update the loop control variables. This statement can
be left blank, as long as a semicolon appears after the condition.
4.The condition is now evaluated again. If it is true, the loop executes and the process repeats
itself (body of loop, then increment step, and then again condition). After the condition
becomes false, the for loop terminates.
59. 1.instead of iteration variable++,we can use iteration variable=iteration variable+1 which is
same as iteration variable++.
for (num=10; num<20; num=num+1)
2.Initialization part can be skipped from loop by declaring the loop variable before the loop.
int num=10;
for (;num<20;num++)
Even though we can skip initialization part but semicolon (;) before condition is must,
without which you will get compilation error.
variations of for loop
60. 3)The increment part can also be skipped and in this case semicolon (;) is must after condition
logic. In this case the increment or decrement part is done inside the loop.
for (num=10; num<20; )
{
//Statements
num++;
}
4) The counter variable can be initialized before the loop and incremented inside the loop.
int num=10;
for ( ;num<20; )
{
//Statements
num++;
}
5) The counter variable can be decremented also.
for(num=20; num>10; num--)
variations of for loop
62. break
Break statement is used to discontinue the normal execution of the code
without any condition and it will jumps out from the current executing loop.
1. When the break statement is encountered inside a loop, the loop is
immediately terminated and program control resumes at the next statement
following the loop.
2. It can be used to terminate a case in the switch statement.
If you are using nested loops ( ie. one loop inside another loop), the break
statement will stop the execution of the innermost loop and start executing
the next line of code after the block.
Syntax:
break;
63. continue
continue is similar to break statement, but it will not jump out of
the loop instead it will stop executing the set instructions inside
loop body for current iteration and jumps to execute the body of
loop for next iterations.Thus the continue statement forces the
next iteration of the loop to take place, skipping any code in
between.
Syntax:
continue;
64. goto
goto statement is a unconditional jump statement. It can be used anywhere
in the program to jump from its current execution to some other lines in the
code. Once it is jumped to some other line, it will continue executing the
codes from there sequentially. It cannot come back again to previous
execution lines. In order to refer to the line it has to jump, we label the
line.Therefore goto statement in C provides an unconditional jump from the
goto to a labeled statement in the same function.
Syntax:
goto label;
…….
……..
label: statement;
65. exit()
exit ( ) is a standard library function used is to terminate the execution of the
program.
The exit() is a system call which is used to exit from the program and returns
the control back to the operating system.
Syntax: exit(0);
66. return
The return statement returns the flow of the execution to the function from
where it is called. This statement does not mandatorily need any conditional
statements. As soon as the statement is executed, the flow of the program
stops immediately and return the control from where it was called. The
return statement may or may not return anything for a void function, but for
a non-void function, a return value is must be returned.
Syntax:
return[expression];
67. return -example
#include <stdio.h>
void print()
{
printf("Happy Learning");
return; //returns the control back to main()
}
void main()
{
print(); //Calling print function from main
}