Control Structures in C
Control Structures in C
CONTROL STATEMENT
Specifies the order in which the various instructions in the program are executed.
The order of statement execution is called the flow of control
Unless specified otherwise, the order of statement execution through a function is linear: one
statement after another in sequence
Some programming statements allow us to:
1
25-09-2024
Conditional Unconditional
Statements statements
DECISION MAKING
Decision making is about deciding the order of execution of statements based on
certain conditions or repeat a group of statements until certain specified conditions
are met.
C language handles decision-making by supporting the following selection/branching
statements,
if statement
switch statement
conditional operator statement
goto statement
2
25-09-2024
if statement
• It is used to control flow of execution of statement.
• It is two-way decision statement and is used in conjuction with an expression
Syntax- if (condition)
{ statement 1; Entry
……………..
}
Test expression False
?
3
25-09-2024
SIMPLE IF STATEMENT
The general form of a
simple if statement is,
if( expression ) condition
evaluated
{
statement inside;
} true
statement outside; false
statement
If the expression is true, then
'statement-inside' it will be
executed, otherwise 'statement-
inside' is skipped and only Next statement
'statement-outside' is executed.
4
25-09-2024
Example
Write a program to check entered character is digit or uppercase or lowercase alphabet.
#include <stdio.h>
int main( )
{ char ch;
printf(“Enter the character”);
scanf(“%c”,&ch);
if (ch>=‘0’ && ch<=‘9’ )
printf(“\n It is a digit");
if (ch>=‘A’ && ch<=‘Z’ )
printf(“\n It is a uppercase alphabet");
if (ch>=‘a’ && ch<=‘z’ )
printf(“\n It is a lowercase alphabet");
return 0;
}
5
25-09-2024
IF...ELSE STATEMENT
The general form of a simple if...else statement is,
if( expression )
{
statement block1;
}
else
{
statement block2;
}
If the 'expression' is true, the 'statement-block1' is executed, else
'statement-block1' is skipped and 'statement-block2' is executed.
EXAMPLE
Write a program to check if a given number is even or odd.
#include<stdio.h>
Int main ()
{
int var;
printf("Enter a Number : ");
scanf("%d",&var);
if(var%2= =0)
{
printf(“%d is even number”,var);
}
else
{
printf(“%d is even number”,var);
}
}
output- Enter a Number :
46
46 is an even number
6
25-09-2024
EXAMPLE
Write a program to check greater of two number.
#include <stdio.h>
int main( )
{
int x,y;
x=15; y=18; Output:
if (x > y ) y is greater than x
{
printf("x is greater than y");
}
else
{
printf("y is greater than x");
}
return 0;
}
Example
Write a program to confirm a year is leap or not.
#include<stdio.h>
int main()
{
int year;
printf(“Enter value of a year:”);
scanf(“%d”, &year);
if(year %100 !=0 && year%4==0 || year%400==0)
printf(“\n The year is a leap year.”);
else
printf(“\n The year is a not leap year.”);
return 0;
}
7
25-09-2024
Example
Write a program to calculate root of a quadratic equation.
#include<stdio.h>
#include<math.h>
int main()
{
float a,b,c,r1,r2,t;
printf(“Enter value of a,b,c:”);
scanf(“%f%f%f”,&a,&b,&c);
t=b*b-4*a*c;
if(t<0)
printf(“\n Roots are imaginary.”);
else
{ r1=(-b+sqrt(t))/2*a;
r2=(-b-sqrt(t))/2*a;
printf(“\n root1=%f”,r1);
printf(“\n root2=%f”,r2);
}
return 0;
}
8
25-09-2024
EXAMPLE
Program to find greatest between
three numbers.
9
25-09-2024
#include <stdio.h>
void main ( ) {
int a,b,c, large;
printf (“Enter the three nunber : ”);
Enter the three number 5 6 4
scanf (“%d%d%d”,&a,&b,&c);
if (a > b) {
if (a > c) Check a > b i.e 5 > 6 , it is false
large = a; Then go to the else part of the
else first if statement .
large = c;
} Check b > c i.e 6 > 4 , it is true
else{
if (b > c)
large =b; So assign the value of b i.e 6 to
else large.
large=c;
}
Out put :
printf(“larger number is %d\n”,large); Enter the three number :
} 564
larger number is 6
/* dangling else, as to
which if statement, else
clause associates */
10
25-09-2024
ELSE IF LADDER
The general form of else-if ladder is
shown in the diagram.
The expression is tested from the top(of if(expression1)
the ladder) downwards. {
statement block1;
As soon as the true condition is found, the }
statement associated with it is executed. else if(expression2)
{
statement block2;
}
else if(expression3 )
{
statement block3;
}
else
default statement;
ELSE IF LADDER
11
25-09-2024
Example
EXAMPLE
Write a program to check the divisibility of 5 and 8.
#include <stdio.h>
int main( )
{
int a=40 ; Output:
if( a%5==0 && a%8==0)
{ divisible by 5
printf("divisible by both 5 and 8");
}
else if( a%8==0 )
{
printf("divisible by 8");
}
else if(a%5==0)
{
printf("divisible by 5");
}
else
{
printf("divisible by none");
}
return 0;
}
12
25-09-2024
Example
WAP to check entered character is digit or uppercase or lowercase alphabet .
#include <stdio.h>
int main( )
{ char ch;
printf(“Enter the character”);
scanf(“%c”,&ch);
if (ch>=‘0’ && ch<=‘9’ )
printf(“\n It is a digit");
else if (ch>=‘A’ && ch<=‘Z’ )
printf(“\n It is a uppercase alphabet");
else if (ch>=‘a’ && ch<=‘z’ )
printf(“\n It is a lowercase alphabet");
else
printf(“\n Special character”);
return 0;
}
POINTS TO REMEMBER
1. In if statement, a single statement can be included without enclosing it into curly
braces { } No curly braces are required in the above case, but if we have more
than one statement inside if condition, then we must enclose them inside curly
braces.
int a = 5;
if(a > 4)
printf("success");
2. == must be used for comparison in the expression of if condition, if you use = the
expression will always return true, because it performs assignment not comparison.
13
25-09-2024
POINTS TO REMEMBER
3. Other than 0(zero), all other values are considered as
true.
In below example, hello will be printed.
if(27)
printf("hello");
SWITCH STATEMENT
1. One of the classic problem encountered in nested if-
else / else-if ladder is called problem of Confusion.
14
25-09-2024
15
25-09-2024
EXAMPLE
main()
{
Output:
int i=2;
switch(i) I am in Case 2
{ I am in Case 3
case 1: printf(“I am in Case 1\n”); I am in Default
case 2: printf(“I am in Case 2\n”);
case 3: printf(“I am in Case 3\n”);
default: printf(“I am in Default\n”);
}
}
POINTS TO REMEMBER
If you want that only case 2 should be executed,
Use a break statement.
16
25-09-2024
EXAMPLE
main()
{ Output:
int i=2;
switch(i)
{ I am in Case 2
case 1: printf(“I am in Case 1\n”);
break;
case 2: printf(“I am in Case 2\n”);
break;
case 3: printf(“I am in Case 3\n”);
break;
default: printf(“I am in Default\n”);
}
}
17
25-09-2024
SWITCH STATEMENT
• The switch statement provides
another way to decide which
statement to execute next.
18
25-09-2024
2. Switch case variables can have only int and char data type. So
float data type is not allowed.
19
25-09-2024
case 1 :
printf("C Programming Language");
break;
20
25-09-2024
VALID
21
25-09-2024
NOT VALID
22
25-09-2024
23
25-09-2024
24
25-09-2024
25
25-09-2024
as preprocessor will
replace occurrence of
MAX by constant value
i.e 2 therefore it is
allowed.
26
25-09-2024
27
25-09-2024
Output : Hi Case 1
The flow of control transfers to statement associated with the first case
value that matches.
If a break statement is not used, the flow of control will continue into the
next case.
28
25-09-2024
If the default case is present, control will transfer to it if no other case value
matches.
If there is no default case, and no other value matches, control falls through to
the statement after the switch.
EXAMPLE
#include<stdio.h>
int main ( )
{
char grade =‘b’ ;
switch (grade)
{
case 'a' :
printf (“value is a.\n") ;
break;
case 'b' :
printf (“value is b.\n") ;
break;
default :
printf (“Default!!\n") ;
} /* End of switch-case structure */
} /* End of main program */
29
25-09-2024
EXAMPLE
#include <stdio.h>
int main ( )
{
char grade =‘b’ ;
switch (grade)
{ Output:
case 'a' : value is b.
printf (“value is a.\n") ;
break; case
'b' :
printf (“value is b.\n") ;
break;
default :
printf (“Default!!\n") ;
} /* End of switch-case structure */
} /* End of main program */
Example
Write a program to perform all arithmetic operations to select their
corresponding operator
case ‘-' :
#include <stdio.h>
printf (“\n sub =%d”,a-b);
int main ( ) break;
case ‘*’ :
{
printf (“\n mul=%d”,a*b);
char op ; break;
case ‘/' :
int a,b; printf (“\n div=%d”,a/b);
printf(“Enter operator for operation +,-,*,/ break;
:”); default :
printf(“\n invalid
scanf(“%c”,&op); operator”);
printf(“Enter 2 numbers”); break;
}
scanf(“%d%d”,&a,&b); return 0;
switch (op) }
{
case ‘+' :
printf (“\n sum =%d”,a+b) ;
break;
30
25-09-2024
EXAMPLE
#include <stdio.h>
int main ( )
{
char grade =‘a’ ;
switch (grade)
{
case 'a' :
case 'A' :
printf ("Good Job!\n") ;
case 'b' :
case 'B' :
printf ("Pretty good.\n") ;
default :
printf ("You are failing!!\n") ;
} /* End of switch-case structure */
} /* End of main program */
EXAMPLE
#include <stdio.h>
int main ( )
{ Output:
char grade =‘a’;
switch (grade) Good Job!
{ Pretty good.
case 'a' : You are failing!
case 'A' :
printf ("Good Job!\n") ;
case 'b' :
case 'B' :
printf ("Pretty good.\n") ;
default :
printf ("You are failing!!\n") ;
} /* End of switch-case structure */
} /* End of main program */
31
25-09-2024
LOOPING
Looping is the process of executing a group of statements repeatedly either a
specified number of times or until some condition is satisfied.
Loops allow program to execute a statement or group of statements multiple times
repeatedly until certain test condition is false.
That is, Loops are used in performing repetitive task in programming.
Loop Consists of
Body of the loop
Control Statement
32
25-09-2024
false
true
Body
TYPE OF LOOPS
Depending upon the position of the control statement in the loop, loop is of two types
Entry-controlled loop/Pretest loop
Exit-controlled loop/Posttest loop
33
25-09-2024
The types of loop where the test condition is tested before the execution of the
loop.
If the test condition is true, then the loop gets the execution, otherwise not.
The body of the loop is executed without testing the condition for the first time.
Then the condition is tested.
If it is true, then the loop is executed again and continues till the result of the test
condition is not false.
34
25-09-2024
Type of loops
Body of Loop
False
Test
Condition
False
True Test
Condition
Body of Loop
True
35
25-09-2024
STEPS IN LOOPING
Initialization of condition variable
Execution of body of the loop
Test the control statement
Updating the condition variable
36
25-09-2024
COMMON LOOPS
Working Principle:
37
25-09-2024
Syntax: condition
evaluated
while (condition)
{
true false
Statements;
}
statement
38
25-09-2024
ANOTHER EXAMPLE
Condition is TRUE for
count = 1, 2, 3, 4,5
int count = 1;
while (count <= 5)
{
printf(“count=%d\t”,count);
count++;
}
OUTPUT
1 2 3 4 5
CONTD…
Condition is FALSE from
the first time.
int count = 10;
while (count <= 5)
{
printf(“HELLO\n”);
count++; NO
}
OUTPUT
39
25-09-2024
CONTD…
Loop control variable is the
variable whose value controls
loop repetition
int count = 1;
while (count <= 5)
{
printf(“HELLO\n”); In this
count++; example,
} count is the
loop control
variable.
main( ) Output :
{
Enter a number : 1452
int n, sum=0, rem;
Sum of digits = 12
printf(“Enter a number : ”);
scanf(“%d”, &n);
while(n>0)
Taking a number as input
{
rem = n%10;
sum = sum + rem; Checking the condition:
n = n/10; True or False
}
printf(“Sum of digits =%d\n”, sum);
}
40
25-09-2024
41
25-09-2024
42
25-09-2024
43
25-09-2024
CONVERSION OF DECIMAL TO
BINARY ???
44
25-09-2024
INFINITE LOOPS
The body of a loop eventually must make the condition false and
terminate at a point.
If not, it is called an infinite loop, which will execute until the user
interrupts the program or until an underflow error occurs.
Example:
int count = 1; Here the condition is
while (count <= 25) always true so it is an
{ infinite loop.
printf(“%d\t”,count);
count = count - 1;
}
45
25-09-2024
46
25-09-2024
1.Character is
#include<stdio.h> Represented in integer
void main() in the form of ASCII
{ internally.
while(‘A’)
printf(“Hello”); 2.Any Character is
} Converted into Non-
zero Integer ASCII
Output : value
while(1) while(100)
{ {
printf(“Good Morning\n”); printf(“Good Morning\n”);
} }
while(‘A’) while(-525)
{ {
printf(“Good Morning\n”); printf(“Good Morning\n”);
} }
47
25-09-2024
NESTED LOOPS
When the body of one loop contains another loop, then it is called a
Nested Loop.
Nested loops contain an outer loop with one or more inner loops.
Here for each iteration of the outer loop ,the inner loop iterates completely.
48
25-09-2024
Working Principle:
do Initially, the statement/s is
{ executed once and then the
Body
Statements; condition is checked.
of
the } while (condition); If the condition is true, the
loop
statement is executed again.
Syntax:
statement
do
{
Statements; true
} while (condition); condition
evaluated
false
49
25-09-2024
#include<stdio.h>
OUTPUT
int main()
5*1=5
{
5 * 2 = 10
int i=1;
5 * 3 = 15
do
5 * 4 = 20
{
5 * 5 = 25
printf(“5 * %d = %d\n”,i,5*i);
5 * 6 = 30
i++;
5 * 7 = 35
}while(i<=10);
5 * 8 = 40
return 0;
5 * 9 = 45
}
5 * 10 = 50
50
25-09-2024
FOR
Syntax:
loop continuation
condition
51
25-09-2024
EXAMPLES
Vary the control variable from 1 to 100 in increments of 1
for (i = 1; i <= 100; i++)
EXAMPLES 2
#include <stdio.h>
void main()
{
/* a program to produce a Celsius to Fahrenheit conversion chart for the
numbers 0 to 100 */
int celsius;
for (celsius = 0; celsius <= 100; celsius++)
printf(“Celsius: %d Fahrenheit: %d\n”, celsius, (celsius * 9) / 5 + 32);
}
52
25-09-2024
In a nested loop, for each value of the outermost counter variable, the complete inner loop will be
executed once
General form
for (loop1_exprs) {
loop_body_1a
for (loop2_exprs) {
loop_body_2
}
loop_body_1b
}
53
25-09-2024
NESTED LOOPS
When the body of one loop contains another loop, then it is
called a Nested Loop.
Nested loops contain an outer loop with one or more inner
loops.
Here for each iteration of the outer loop ,the inner loop iterates
completely.
Types of nested loops
Nested for Loop
Nested while loop
Nested do-while Loop
Note: There can be mixed type of nested loop i.e. a for loop
inside a while loop, or a while loop inside a do-while loop.
54
25-09-2024
55
25-09-2024
56
25-09-2024
Syntax Flowchart
while (condition1)
{
statement(s);
while (condition2)
{
statement(s);
... ... ...
}
... ... ...
}
EXAMPLE
Outer
while loop
count1 = 1;
while (count1 <= 10)
Inner while
{
loop
count2 = 1;
while (count2 <= 20) For each value of
{ count1…
printf("Hello"); count2 will be executed 20
times.
count2++;
} count1 has 10 values &
count1++; count2 has 20 values,
} therefore Hello will be
printed 10 * 20 times.
57
25-09-2024
58
25-09-2024
59
25-09-2024
• Break statement
• Continue statement
• Goto Statement
60
25-09-2024
BREAK
The break statement in C programming has the following two
usages −
1. When a break statement is encountered inside a loop, the loop
is immediately terminated and the 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, the break statement will stop the
execution of the innermost loop and start executing the next line of
code after the block.
.
Syntax
The syntax for a break statement in C is as follows −
break;
61
25-09-2024
62
25-09-2024
63
25-09-2024
CONTINUE STATEMENT
The continue statement in C programming works somewhat
like the break statement.
Instead of forcing termination, it forces the next iteration of the
loop to take place, skipping any code in between.
For the for loop, continue statement causes the conditional test
and increment portions of the loop to execute.
For the while and do...while loops, continue statement causes
the program control to pass to the conditional tests.
64
25-09-2024
65
25-09-2024
BREAK VS CONTINUE
break causes an exit from the
innermost enclosing loop
66
25-09-2024
do-while -- the loop body is always executed once. After that, the expression is
tested, if the result is false, the loop body is not executed again
C GOTO STATEMENT
The goto statement is used to alter the normal sequence
of a C program.
67
25-09-2024
goto label;
... .. ...
... .. ...
... .. ...
label:
statement;
sum += number;
}
jump:
average=sum/(i-1);
printf("Sum = %.2f\n", sum);
printf("Average = %.2f", average);
return 0;
}
68
25-09-2024
sum += number;
}
jump:
average=sum/(i-1);
printf("Sum = %.2f\n", sum);
printf("Average = %.2f", average);
return 0;
}
sum += number;
}
jump:
average=sum/(i-1);
printf("Sum = %.2f\n", sum);
printf("Average = %.2f", average);
return 0;
}
69
25-09-2024
REASONS TOstatement
The use of goto AVOID GOTO
may lead STATEMENT
to code that is buggy and hard
to follow.
For example
REASONS TOstatement
The use of goto AVOID may GOTO STATEMENT
lead to code that is buggy and
Also, goto statement allows you
hard to follow.
to do bad stuff such as jump out
of scope.
For example
That being said, goto statement
can be useful sometimes.
For example: to break from
nested loops.
70