4 Sitd109 Control-Structures
4 Sitd109 Control-Structures
CONTROL STRUCTURES
Definition
Control structures represent the forms by which statements in a program are executed. Flow of control
refers to the order in which the individual statements, instructions or function calls of a program are
executed or evaluated.
The kinds of control flow statements supported by different languages vary, but can be categorized by
their effect:
continuation at a different statement i.e. unconditional jump e.g. GoTo statements
executing a set of statements only if some condition is met i.e. choice
executing a set of statements zero or more times, until some condition is met i.e. loop
executing a set of distant statements, after which the flow of control usually returns e.g.
subroutines/functions
3. Repetition/Iterative structures
This is where a group of statements in a program may have to be executed repeatedly until some
condition is satisfied. These include while, do/while and for
32
SELECTION STRUCTURES
(a) THE IF SELECTION STRUCTURE
– Used to choose among alternative courses of action i.e. the if statement provides a junction at which
the program has to select which path to follow. The if selection performs an action only if the
condition is true,
General form
If (expression)
statement
Pseudocode:
As in
if (marks>=600)
printf(“Passed”);
If condition is true
– Print statement executed and program goes on to next statement
– If false, print statement is ignored and the program goes onto the next statement
NB/ Indenting makes programs easier to read
true
grade >= 60 print “Passed”
false
NB/ The statement in the if structure can be a single statement or a block (Compound statement).
If it’s a block of statements, it must be marked off by braces.
33
if (expression)
{
Block of statements
}
As in
If (salary>5000)
{
tax_amount = salary * 1.5;
printf(“Tax charged is %f”, tax_amount);
}
While if only performs an action if the condition is true, if/else specifies an action to be performed both
when the condition is true and when it is false. E.g.
Pseudocode:
If student’s grade is greater than or equal to 60
Print “Passed”
else
Print “Failed”
false true
grade >= 60
Example
if (x >=100)
{
printf(“Let us increment x:\n”);
x++;
}
else
34
– Test for multiple cases/conditions.
– Once a condition is met, the other statements are skipped
– Deep indentation usually not used in practice
Example
#include <stdio.h>
main()
{
int marks;
printf("Please enter your MARKS:");
scanf("%d", &marks);
Syntax
The syntax for a nested if statement is as follows:
if (boolean_expression 1)
{
/* Executes when the boolean expression 1 is true */
if(boolean_expression 2)
35
{
/* Executes when the boolean expression 2 is true */
}
}
You can nest else if...else in the similar way as you have nested if statement.
Example
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 100;
int b = 200;
/* check the boolean condition */
if( a = = 100 )
{
/* if condition is true then check the following */
if( b = = 200 )
{
/* if condition is true then print the following */
printf("Value of a is 100 and b is 200\n" );
}
}
return 0;
}
When the above code is compiled and executed, it produces the following result:
Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200
Syntax
The syntax for a switch statement in C programming language is as follows:
switch(expression)
{
case constant-expression
statement(s);
break;
case constant-expression :
statement(s);
break;
/* you can have any number of case statements */
default :
statement(s);
}
36
The following rules apply to a switch statement:
1) You can have any number of case statements within a switch. Each case is followed by the value
to be compared to and a colon.
2) The constant-expression for a case must be the same data type as the variable in the switch
3) When the variable being switched on is equal to a case, the statements following that case will
execute until a break statement is reached.
4) When a break statement is reached, the switch terminates, and the flow of control jumps to the
next line following the switch statement.
5) 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.
6) 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.
#include<stdio.h>
void main()
{
char grade;
switch (grade)
{
case 'A':
printf("Excellent!\n");
break;
case 'B':
printf("Very Good!\n");
37
break;
case 'C':
printf("Good!\n");
break;
case 'D':
printf("Work harder!\n");
break;
default:
printf("Fail!\n");
}
}
38
}
When the above code is compiled and executed, it produces the following result:
REPETITION/ITERATIVE/LOOP STRUCTURES
A loop statement allows the execution of a statement or a group of statements multiple times until a
condition either tests true or false. There are two types of loops: Pre-test and post-test loops.
In a pretest loop, a logical condition is checked before each repetition to determine if the loop should
terminate. These loops include:
– while loop
– for loop
Post-test loops check a logical condition after each repetition for termination. The do-while loop is a post-
test loop.
The statement(s) may be a single statement or a block of statements. The loop iterates while the condition
is true.
When the condition becomes false, program control passes to the line immediately following the loop.
39
Example
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 10; //loop index
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Syntax
The syntax of a for loop in C programming language is:
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.
40
3. After the body of the for loop executes, the flow of control jumps back up to the update
expression. This statement allows you to update any 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.
After the condition becomes false, the for loop terminates.
Flow Diagram
Example
#include <stdio.h>
int main ()
{
int a;//loop index
/* for loop execution */
for(a = 10; a < 20; a++)
{
printf("value of a: %d\n", a);
}
return 0;
}
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
41
value of a: 17
value of a: 18
value of a: 19
Syntax
do
{
statement(s);
}while( condition );
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.
Example
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 10;
/* do loop execution */
do
{
printf("value of a: %d\n", a);
a = a + 1;
}while( a < 20 );
return
42
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
The syntax for a nested while loop statement in C programming language is as follows:
while(condition)
{
while(condition)
{
statement(s);
}
statement(s);
}
The syntax for a nested do...while loop statement in C programming language is as follows:
do
{
statement(s);
do
{
statement(s);
}while( condition );
}while( condition );
43
A final note on loop nesting is that you can put any type of loop inside of any other type of loop. For
example, a for loop can be inside a while loop or vice versa.
Example
#include <stdio.h>
int main()
{
int n, c, k;
return 0;
}
Result:
If the user interred 5 as the number of rows, the output would be:
1
12
123
1234
12345
TERMINATING LOOPS
• Counter-controlled loops - a loop controlled by a counter variable, generally where the number of times
the loop will execute is known ahead of time especially in for loops.
• Event-controlled loops - loops where termination depends on an event rather than executing a fixed
number of times for example when a zero value is keyed in or search through data until an item is found.
Used mostly in while loops and do-while loops.
Using a Sentinel
• The value -999 is sometimes referred to as a sentinel value. The value serves as the “guardian” for the
termination of the loop. It is a good idea to make the sentinel a constant:
#define STOPNUMBER -999
while (number != STOPNUMBER) ...
44
BRANCHING STATEMENTS
(a) BREAK STATEMENT IN C
The break statement has the following two uses:
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.
3. If you are using nested loops (i.e., 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.
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 10;
/* do loop execution */
do
{
if( a = = 15)
{
/* skip the iteration */
break;
}
printf("value of a: %d\n", a);
a++;
}while( a < 20 );
return 0;
}
Example
//program to demonstrate the working of continue statement in C programming
# include <stdio.h>
int main(){
int i,num,product;
for(i=1,product=1;i<=4;++i){
printf("Enter num%d:",i);
scanf("%d",&num);
if(num==0)
continue; /*In this program, when num equals to zero, it skips
the statement product*=num and continue the loop. */
product*=num;
}
printf("product=%d",product);
45
return 0;
}value of a: 19
Syntax
The syntax for a goto statement in C is as follows:
goto label;
..
.
Example
#include <stdio.h>
int main ()
{
/* for loop execution */
int a,userinput,sum=0;
sum+=userinput;
}
jump:
46
printf("The sum of the values is %d\n", sum);
return 0;
}
The last of the branching statements is the return statement. The return statement exits from the current
function, and control flow returns to where the function was invoked. The return statement has two
forms: one that returns a value, and one that doesn't. To return a value, simply put the value (or an
expression that calculates the value) after the return keyword.
return count;
The data type of the returned value must match the type of the method's declared return value. When a
function is declared void, use the form of return that doesn't return a value.
return;
#include <stdio.h>
int main ()
{
for( ; ; )
{
printf("This loop will run forever.\n");
}
return 0;
}
When the conditional expression is absent, it is assumed to be true. You may have an initialization and
increment expression, but C programmers more commonly use the for(;;) construct to signify an infinite
loop.
NOTE: You can terminate an infinite loop by pressing Ctrl + C keys.
47