Chapter 2
Control Structures
FE – C Programming
Prof. Namrata Jiten Patel
Assistant Professor
Dept. of Computer Engineering,
SIES Graduate School of Technology
Learning Objectives:
1. To understand basics of control structure
2. To make students thorough about If-else, Nested If- else control
structures
3. To make students thorough about Switch statements
4. To make students thorough about Looping, do while, while loop
5. To make students thorough about Break and continue statements
2
Introduction
• A C application begins executing with the first line of the main() function
and proceeds statement by statement until it gets to the end of the main()
function.
• In C, any sequence of statements can be grouped together to function as a
syntactically equivalent single statement by enclosing the sequence in
braces.
• This grouping is known as statement block or compound statement.
• Every function has a function body consisting of a set of one or more
statements, i.e., a statement block
3
Introduction
• The order in which statements are executed in a running program is
called the flow of control.
• Control statements embody the decision logic that tells the executing
program what action to carry out next depending on the values of certain
variables or expression statements.
• The control statements include selection, iteration, and jump statements
that work together to direct program flow.
4
Introduction
5
Introduction
• A selection statement is a control statement that allows choosing between
two or more execution paths in a program
• Each decision is based on a boolean expression (also called a condition or
test expression), which is an expression that evaluates to either true or false.
The result of the expression determines which statement is executed next.
• The programming mechanism that executes a series ofstatements repeatedly
a given number of times, or until a particular condition is fulfi lled, is called
a loop. The construct used for loop is known as iteration statement.
• Jump statements transfer the control to another point of the program. Jump
statements include goto, break, continue and return.
6
CONDITIONAL EXECUTION AND SELECTION
• When dealing with selection statements, there are generally three
versions: one-way, two-way, and multiway.
• One-way decision statements do a particular thing or they do not.
• Two-way decision statements do one thing or do another.
• Multi-way decision statements can do one of many different things
depending on the value of an expression
7
CONDITIONAL EXECUTION AND SELECTION
• One-way decisions using if statement
if(TestExpr)
stmtT;
TestExpr is the test expression. stmtT can be a simple
statement or a block of statements enclosed by curly
braces {}.
8
CONDITIONAL EXECUTION AND SELECTION
• Two-way decisions using if –else statement
if(TestExpr)
stmtT;
else
stmtF;
If the test expression TestExpr is true, stmtT will be executed; if the
expression is false, stmtF will be executed. stmtT and stmtF can be single
or a block of statements.
Kalyani N Pampattiwar 9
CONDITIONAL EXECUTION AND SELECTION
• Multi way decision
10
CONDITIONAL EXECUTION AND SELECTION
• Multi way decision
11
CONDITIONAL EXECUTION AND SELECTION
Kalyani N Pampattiwar 12
If-else ladder
• WAP to print the garde according to the score secured by student.
For score>=90----A garde
For score>=80----B garde
For score>=70----C garde
For score>=60----D garde
Otherwise Grade=F
Kalyani N Pampattiwar 13
Nested -if
• When any if statement is written under another if statement, this cluster is called
a nested if.
• The if statement that tests for divisibility by 5 is located inside of the if statement
that tests for divisibility by 3 therefore it is considered to be a nested if statement.
if (number % 3 == 0)
{
printf(“number is divisible by 3. \n”);
if (number % 5 == 0)
{
printf(“number is divisible by 3 and 5. \n”);
}
}
14
Dangling else problem
• This classic problem occurs when there is no matching else for each if.
To avoid this problem, the simple C rule is that always pair an else to the
most recent unpaired if in the current block.
• If TestExprA is evaluated to true, then execution moves
to the nested if and evaluates TestExprB.
• If TestExprB is evaluated to true then stmtBT will be
executed.
• If TestExprA is evaluated to false, then stmtAF is
executed. But in the code above, the else is
automatically paired with the closest if. But, it is
needed to associate an else with the outer if also.
• The solution is either of the following:
- Use of a null else
- Use of braces to enclose the true action of the second
if.
15
Dangling else problem
• Now, in both the
solutions, if the
expression TestExprA
evaluates to false then
the statement stmtAF
will be executed.
• If it evaluates to true,
then it checks for
TestExprB.
• If TestExprB evaluates
to true then statement
stmtBT will be executed.
Kalyani N Pampattiwar 16
What is the O/P?
#include <stdio.h>
int main()
{
int a = 2;
int b = 2;
if (a == 1)
if (b == 2)
printf(“a was 1 and b was 2\n”);
else
printf(“a wasn’t 1\n”);
return 0;
}
https://www.menti.com/f36fcugt9a
17
Corrected program
In order to achieve the effect that the programmer probably originally
intended, it is necessary to re-arrange the program in the following form.
int main()
{
int a = 2;
int b = 2;
if (a == 1)
{
if (b == 2) printf(“a was 1 and b was 2\n”);
}
else printf(“a wasn’t 1\n”);
return 0;
}
18
Check your progress
1. What will be the output of (b)
the following programs? int main()
(a) {
int main() printf(“Hi!”);
{ if(!1)
printf(“Hi!”); printf(“Bye”);
if(-1) return 0;
printf(“Bye”); }
return 0; Output: Hi!
}
https://www.menti.com/
f36fcugt9a
Output: Hi!Bye
19
Check your progress
(c) (d) int main()
float x = 199.9; {
if( x < 100) int i= -1;
printf(“one ”); unsigned int j =1;
if(x < 200) if(i<j)
printf(“two ”); printf(“Less”);
if(x < 300) else
printf(“three ”); printf(“Greater”);
return 0;
Output: two three }
Output: Greater
20
Switch Statements
• It belongs to the category of selection/ branching control structures
• The switch statement in C is an alternate to if-else-if ladder
statement
• It allows us to execute multiple operations for the different possible
values of a single variable called switch variable.
• Here, We can define various statements in the multiple cases for the
different values of a single variable.
21
Switch Statements
The syntax of switch statement in c language:
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
is given below:
22
Rules for switch statement in C language
1) The switch expression must be of an integer or character type.
2) The case value must be an integer or character constant.
3) The case value can be used only inside the switch statement.
4) The break statement in switch case is not must. It is optional. If
there is no break statement found in the case, all the cases will be
executed present after the matched case. It is known as fall
through the state of C switch statement.
23
Rules for switch statement in C language
We are assuming that there are following variables.
int x,y,z;
char a,b;
float f;
24
Flowchart of switch statement in C
25
Functioning of switch case statement
• First, the integer expression specified in the switch statement is
evaluated.
• This value is then matched one by one with the constant values given
in the different cases.
• If a match is found, then all the statements specified in that case are
executed along with the all the cases present after that case including
the default statement.
• No two cases can have similar values.
• If the matched case contains a break statement, then all the cases
present after that will be skipped, and the control comes out of the
switch.
• Otherwise, all the cases following the matched case will be executed.
26
enter a number:4 number is not equal to 10, 50 or 10
enter a number:4 number is not equal to 10, 50 or 100
Example of switch case statement
#include<stdio.h> default:
int main(){ printf("number is not equal to 10, 50 or 100");
int number=0; }
printf("enter a number:"); return 0;
scanf("%d",&number); }
switch(number){ O/P
case 10:
printf("number is equals to 10");
Enter a number :4
break; -----------------
case 50: Enter a number:50
printf("number is equal to 50");
break;
-----------------
case 100:
printf("number is equal to 100");
break;
27
Iterations
• A loop allows one to execute a statement or block of statements
repeatedly.
• There are mainly two types of iterations or loops
Unbounded loop/iterations
Bounded loop/iterations
28
• Bounded Iteration
Repetition is implemented by constructs that allow a determinate
number of iterations
Example :for loop
• Unbounded Iteration
In many occasions when one does not know ,ahead of time ,how
many iterations may be required .
Example: while loop and
do-while loop
29
A loop can be either be a pre-test loop
or post-test loop .
Pre-test Loop Post-test loop
• The condition is checked before the • The code is always executed
beginning of each iteration .
once ,At the completion of the
• If the test expression evaluates to true
loop code ,the test expression
, the statements associated with the
pre- test loop construct are executed
is tested .
and the process is repeated till the • If the test expression is true
test expression becomes false. then loop repeats and if false
or then terminates.
• If the test evaluates false ,the
statement associated with the
constructs are skipped and the
statement next to the loop is executed
30
Loop Variations :pre-test and Post-
test loops
31
In addition to condition/test expression the other
two processes are associated with almost all loops .
• These are: • Initialization :It is the statement
that assigns the initial value to
Initialization the loop control variable.
• Updating :The action that
Updating
changes the test expression
from true to false .
32
Comparison between pre-test and
post-test loop
Pre-test loop Post-test loop
Initialization Once Once
Number of tests N+1 n
Actions executed n n
Updating executed n n
Minimum Iteration Not even once Atleast once
33
While construct
• While loop is pre-test loop
• It uses a test expression to
control the loop.
While construct
34
Expanded syntax of while and its
flowchart representation
#include<stdio.h>
int main()
{
int c;
c=5;
while(c>0)
{
printf(“\n%d”,c);
c=c-1;
}
return 0;
}
35
for Construct
• The loop formed by using the • for(initialization;Testexpr;Updating)
for statement is generally called {
a determinate or definite loop . Stmt
• (Because the programmer knows }
exactly how many times it will
repeat.)
• Initialization: First one to
execute
• Testexpr: represents a test
expression that must be true for
the loop to continue execution
• Updating :The statement
contained here are executed
every time through loop
• Stmt: Single block or block of
statement.
36
The Sequence of events that
generate the iteration using for loop
• Evaluate the Initialization expression
• If the value of the Testexpr is false ,terminate and go to next line of stmt
Otherwise continue with the same operation.
• Execute the statement or block of statement
• Evaluate Update expression.
37
In general how many times does the
body of for() loop is executed
• for(i=m;i<=n;i++)
Ans:(n-m)+1 times
• for(i=m;i<n;i++)
Ans:(n-m) times
• for(i=m;i<n;i+=x)
Ans:(n-m)/x
38
Example of for() loop
#include<stdio.h>
int main(){
int i=0;
for(i=1;i<=10;i++){
printf("%d \n",i);
}
return 0;
}
39
Points to be remembered for ‘for
’loop
• EVEN THOUGH 3 EXPRESSION IS NOT PRESENT IN THE
for STATEMENT ‘;’ MUST BE PRESENT.
• ANY INITIALIZATION STATEMENT CAN BE USED IN THE
FIRST PART OF THE FOR LOOP .
• MULTIPLE INITIALIZATION SHOULD BE SEPERATED
WITH A COMMA OPERATOR.
40
Do-while COnstruct
• do while construct is another #include<stdio.h>
construct that is closely related int main(){
to the while construct.
int x=1;
• The do keyword is placed on a
line of a code at the top of the int count=0;
loop . do{
• A block of statement follows it scanf(“%d”,&x);
with a test expression after the if(x>0){count+=1;}
keyword while ,at the bottom of
the loop. }while(x>=0);
return 0;
}
41
Do while
While
C do-while
Loop
42
While and do-while loop
1. While loop is indeterminate 1. do-while loop is
or unbounded loop. indeterminate or unbounded
loop.
2. While is pre-test loop 2. Do-while loop is considered
to be post-test loop since the
loop is located after the body
3. While does not executes for of the loop.
any false condition 3. Do-while guarantees to
execute at least once even if
4. Flowchart representation is the condition is false
different than do-while 4. Flowchart representation is
different than while loop
43
Thank You!!
44