CONTROL STRUCTURE
Introduction
A control structure is simply a pattern for controlling the flow of a
program module.
These statements are commonly referred to as control statements
because they “control” the flow of program execution.
The three fundamental control structures of a structured
programming language are:
1. Sequence
2. Selection
3. Iteration
Introduction cont’d…
One of the most important aspects of programming is
controlling which statement will execute next. Control
structures/Control statements enable a programmer to
determine the order in which program statements are
executed.
These control structures allow you to do two things:
1. Skip some statements while executing others, and
2. Repeat one or more statements while some condition is true.
Sequential Program Control
By sequential we mean "in sequence," one-after-the-other.
Sequential logic is the easiest to construct and follow.
Essentially you place each statement in the order that you want them
to be executed and the program executes them in sequence from the
Start statement to the End statement.
For instance, If your program included 20 basic commands, then it
would execute those 20 statements in order and then quit.
Control Statements
Control statements change the flow of a program based on
specified conditions. There are two types of control
statements that is:
1) Branching control
- if
- switch
2) Looping/Iteration control
- for
- while
Selection/Branching Control
It is common that you will need to make a decision about some
condition of your program's data to determine whether certain
statements should be executed.
A selection-control statement allows you to make "decisions" in your
code about the current state of your program's data and then to take
one of two alternative paths to a "next" statement.
All decisions are stated as "yes/no" questions.
When a program is executed, if the answer to a decision is "yes" (or
true), then the left branch of control is taken. If the answer is "no" (or
Branching Statements
if statement
The if statement is a powerful decision-making statement
and is used to control the flow of execution of statements.
It is a two-way decision statement and is used in conjunction
with an expression, and takes the following form; if (test
expression) statement;
if statement
The if statement may be implemented in different forms
depending on the complexity of conditions to be tested as
follows:
1. Simple if statement
2. If …. else statement
3. Nested if ….. else statement
Simple if statement
The general form of a simple if statement is:
if (test expression) statement;
The statement block may be a single statement or a group of
statements.
If the test expression is true the statement block is executed;
otherwise it will be skipped and the program control jumps to
statement .
E.g.
Example
Write a program to input voter’s name and age then display
“you are allowed to vote” if age is equal or greater than 18.
Write a program to input student name, maths, english and
kiswahili then calculate total and average marks and display
the result. If average marks is greater or equal to 50 it should
display “pass” else it should display “fail”.
Algorithm
Input voter name
Input voter age
If (age>=18) display “You are allowed to vote”
START
Input voters’
name and age
If YES
age> Vote
=18
NO
Not
allowed
to vote
STOP
Program code
# include <stdio.h> scanf (“%d”,& age);
int main() if (age>=18) printf (“Vote”);
{ char vname[10]; else printf (“Not allowed to
vote”);
int age;
}
printf (“Enter voters’ name”);
return 0;
scanf (“%s”,& vname);
}
printf (“Enter age”);
The if …… else Statement
It is used to decide between two courses of action.
The if … else statement is an extension of the simple if statement. Its general
form is;
if (test expression) true-statement(s);
else false-statement(s);
Example
If(avg>50) printf(“pass”);else printf(“fail”);
If the expression is TRUE, statement1 is executed; statement2 is skipped.
If the expression is FALSE, statement2 is executed; statement1 is skipped.
Example
Write a program to enter product name, quantity and price
then calculate total price. If total price is greater than 10000
a discount of 10% is offered. Otherwise no discount is
offered. Let the program display the discount and net price.
If (tprice>10000) disc=0.1*tprice;
Else disc=0;
Netprice=tprice-disc;
Design a flow chart and hence implement a program to input
employee name, hours worked and rate per hour then calculate
gross pay. Let the program calculate tax of 15% when gross
pay is greater than or equal to 50000 and 10% when gross pay
is less than 50000.
Operators
Arithmetic operators
+ , - , *, /
++ increment operator – increase a value by
one.
-- decrement operator – Decrease a value by
one.
Conditional/Relational operators
They are used to compare values
< - less than
== - Equality
<= Less or equal to
> Greater than
>= Greater than or equal to
!= Not equal to
Logical operators
AND operator (&&) – Applies when both operands/conditions
are true.
OR operator (||) – Applies when both or either condition is
true.
NOT operator (!) – Negates OR or AND operators. E.g. !&&
If (rain==“yes” && temp<20) prinf (“Wear a Jacket”);
The if…elseif statement
When a series of decisions are involved, we may have to use more than one
if .. else statements. The general form for nested if…. elseif statement is;
if(expression 1)
{
statement 1; /* Executes when the expression 1 is true */
}
else if( expression 2)
{
statement 2; /* Executes when the expression 2 is true */
}
else if( expression 3)
{
statement 3; /* Executes when the expression 3 is true */
}
else
{
statement 4; /* executes when the none of the above condition is true */
}
Example
Write a program to input employee name, hours worked and
rate per hour then calculate gross pay = hours worked * rate
per hour. Tax is charged based on gross pay as follows:
Gross pay tax
Over 100000 20%
Between 50000 and 10%
100000
Below 50000 0
Program code
Design a flowchart and hence write a program prompts the
user to enter the student’s marks and then it displays the
grade corresponding to the marks as shown in the table
Marks Grade
80 - 100 A
60 - 79 B
50 - 59 C
40 - 49 D
0 - 39 Fail
Nesting if …. else Statements
The general form for nested if…. else statement is;
if (test-conditions-1)
{
if (test-conditions-2);
statement-1;
else statement - 2; } statement-x ;
}
If the condition-1 is true, condition-2 is tested and if
condition-2 is true then and statement-1 will be evaluated
otherwise statement-2 will be executed if condition-2 is
false.
If condition-1 is false control is transferred to the statement-
x.
Example
If (gender==“female)
{if (mean>=60) printf (“Admit student”);
else printf (“don’t admit”);}
Else printf (“Not admissible”);
Example
A bank‟s policy is to a 2% bonus on the ending
balance at the end of the year (31st December)
irrespective of the balance, and a 5% bonus is also
given to female account holders if the balance is more
than 50,000.
main()
if (sex is female)
{ if (balance > 50000)
{ bonus = 0.05 * balance; else bonus = 0.02 *
balance; } else { bonus = 0.02 * balance; } balance
= balance + bonus;
The Switch statement
The switch statement selects from a number of alternatives. The switch
statement has the following components.
The switch statement- It includes the variable to be tested in brackets.
Braces { }- Used to indicate the start and end of the switch statement block.
Case statement- Each case statement specifies a value to compare with the
value specifies in the switch statement.
Default – It is an optional statement included to indicate the message or
statement to be executed if none of the case statements were matched.
Syntax
switch (value)
{
case 1: first alternative statement;
break;
case 2: second alternative statement;
break;
case 3: last alternative statement;
break;
default: default statement;
}
NB: Switch statement can only be used for ordinal
data types such as character and integer data types.
Float data types are not allowed as switch values.
Example
1. Write a Program to input a number then display the
number in words. (1 to 5).
2. Write a program to input grade. If grade is A, it
should display Excellent, grade B - Good, Grade C –
Average and D- Below average.
# include <stdio.h> break;
int main() case 5: printf(“Five”);
{ break;
int num; default: printf(“Error”);
Printf(“Enter number”); }
Scanf(“%d”,&num); return 0;
Switch (num) }
{
case 1: printf(“One”);
break;
case 2: printf(“Two”);
break;
case 3: printf(“Three”);
break;
case 4: printf(“Four”);
# include <stdio.h> If (num==4)}
int main() {printf(“Four”);}
{ If (num==5)
int num; {printf(“Five”);}
Printf(“Enter number”); return 0;
Scanf(“%d”,&num); }
If (num==1)
{ printf(“One”);}
If (num==2)
{printf(“Two”);}
If (num==3)
{printf(“Three”);}
Write a program to input two numbers and a sign.
Then perform calculations according to the sign
entered as shown below.
Sign Calculation
+ Add the two number
- Subtract the two numbers
* Multiply the two numbers
/ Divide the two numbers
# include <stdio.h>
int main() case ‘-’: ans=x-y;
{ int x,y; break;
float ans; case ‘*’: ans=x*y;
char sign; break;
Printf(“Enter number”); case ‘/’: ans=x/y;
Scanf(“%d”,&x); break;
Printf(“Enter 2nd number”); default: printf(“Error”);
Scanf(“%d”,&y); Printf ( “answer %f”,ans);
Printf(“Enter sign”); }
Scanf(“%c”,&sign); return 0;
Switch (sign) }
{ case ‘+’: ans=x+y;
break;
Iteration/Loop control structure
The purpose of loop statements is to repeat one or more
statements a given number of times until certain conditions
occur.
A programming loop is one that forces the program to go back
up again and thus you can execute lines of code repeatedly.
This type of control statement is what makes computers so
valuable. A computer can repeatedly execute the same
instructions over-and-over again without getting bored with
There are three kinds of loop statements in C. That is:
while
do…while
for
for Loop
A for loop is a repetition control structure that allows you to
efficiently write a loop that needs to execute a specific number
of times.
A for loop is useful when you know how many times a task is to
be repeated.
Syntax:
The syntax of a for loop is:
for(initialization; test-condition; increment)
{
Statements;
}
Note: the three sections in the for () statement must be separated by semicolons
Example
Write a program to display numbers
10,11,12,13,14……..19.
int main()
{int x;
for(x = 10; x < 20; x++)
{
printf("value of x : %d " , x );
printf("\n");
}
return 0;
Use for control structure to:
Write a program to display numbers 10,9,8,7…1.
Write a program to enter employee name, hours worked
and rate per hour then calculate gross salary of 4
employees.
while loop
The while statement continually executes a block of statements while
a particular expression/condition is true.
Its syntax can be expressed as:
while (expression)
{
statement(s)
}
NB: In while loop, the test is done at the start. i.e. test then execute.
The while statement evaluates expression, which
must return a boolean value. If the expression
evaluates to true, the while statement executes the
statement(s) in the while block.
The while statement continues testing the expression
and executing its block until the expression evaluates
to false.
while flow chart
While
expressi No
on
Yes
Statement(s)
counter
A counter is an integer variable that counts the
number of loops.
It is initialized before the loop and incremented or
decremented within the loop.
It is used when dealing with predefined number of
loops.
Examples
Write a program to display the word “hallo” 10 times.
Write a program to display the numbers 1,2,3,4,5,6,7,8.
Write a program to display the numbers 2,4,6,8………12.
Write a program to input student name, maths, english
and kiswahili and calculate total and average marks of
five students.
# include <stdio.h>
int main()
{ int counter;
counter = 0;
while(counter<=10)
{ printf (“ \nHallo”);
counter++;
}
}
start
Count=0
While No
(count<1
0)
Yes
Display Hallo
Count++
stop
# include <stdio.h>
Int main()
{ int counter;
counter = 1;
while(counter<=8)
{ printf (“%d”, counter);
counter++;
}
}
# include <stdio.h>
Int main()
{ int counter;
counter = 0;
while(counter<=12)
{ printf (“%d”, counter);
counter=counter +2;
}
}
# include <stdio.h> printf (“\n”);
int main() counter--;
{ int counter; }
counter = 10; return 0;
while(counter>=1) }
{ printf (“%d”,counter);
#include <stdio.h> printf (“Enter English”);
int main() scanf(“%d”,&eng);
{int count; printf (“Enter Kiswahili”);
int mat,eng,kis,tot; float avg; scanf(“%d”,&kis);
char sname[10]; tot=mat+eng+kis;
count=0; avg=tot/3;
while (count<5) Printf (“Total is %d \n”,tot);
{ printf (“Enter student name”); Printf (“Average is %f \n”,avg);
scanf(“%s”,&sname); Count++;
printf (“Enter mathematics”); } return 0;
scanf(“%d”,&mat); }
do while
Unlike for and while loops, which test the loop condition at the top of the loop, the
do...while loop in C programming language checks its condition at the bottom of
the loop.
A do...while loop is similar to a while loop, except that a do...while loop is
guaranteed to execute at least one time. Do…while is used when the body of the
loop needs to be executed first before evaluating the test-condition.
do
statement(s)
}
# include <stdio.h>
Int main()
{ int counter;
counter = 10;
do { printf (“%d”,counter);
printf (“\n”);
counter=counter-1;
} while(counter>=1);
return 0;
}