Lecture 5 - Control Structures
Lecture 5 - Control Structures
Introduction
Control structures represent the forms by which statements in a program are executed.
Basically, program statements are executed in the sequence in which they appear in the program.
The structure uses a test condition statement, which upon evaluation by the computer gives rise to
certain conditions which may evaluate to a Boolean true or false. Based on the outcome of the test
condition, the computer may execute one or more statements.
In reality, a logical test using logical and relational operators may require to be used in order to
determine which actions to take (subsequent statements to be executed) depending on the outcome of
the test. This is selection. For example:
In addition, a group of statements in a program may have to be executed repeatedly until some
condition is satisfied. This is known as looping. For example, the following code prints digits from 1 to 5.
for(digit = 1; digit < = 5; digit++)
printf(“\n %d”, digit)
Selection Structure
The if statement
The if statement provides a junction at which the program has to select which path to follow. The
general form is :
if(expression)
statement;
If expression is true (i.e. non zero) , the statement is executed, otherwise it is skipped. Normally the
expression is a relational expression that compares the magnitude of two quantities ( For example x > y
or c = = 6)
Examples
(i) if (x<y)
printf(“x is less that y”);
The statement in the if structure can be a single statement or a block (compound statement).
If the statement is a block (of statements), it must be marked off by braces.
if(expression)
{
block of statements;
}
Example
if(salary>5000)
{
tax_amt = salary *1.5;
printf(“Tax charged is %f”, tax_amt);
}
if - else statement
The if else statement lets the programmer choose between two statements as opposed to the simple if
statement which gives you the choice of executing a statement (possibly compound) or skipping it.
The general form is:
if (expression)
statement;1
else
statement2;
If expression is true, statement1 is executed. If expression is false, the single statement following the
else (statement2) is executed. The statements can be simple or compound.
Example:
if(x >=0)
{
printf(“let us increment x:\n”);
x++;
}
else
printf(“x < 0 \n”);
if (expression 1)
statement 1;
else if (expression 2)
statement 2;
else if (expression 3)
statement 3;
-------------
else
statement n;
(Braces still apply for block statements) In this structure expression 2 is only tested if condition one is
false. Explain how execution of the statements occurs.
Examples:
1. A program to call students marks, grade and output the marks and grade.
2. A program to determine the job group of an employee given some scales.
3. A program to prompt for three values a, b and c and determine which is the greatest value.
Example
if(sale_amount>=10000)
Disc= sal_amt* 0.10; /*ten percent/
else if (sal_amt >= 5000 && sal_amt < 1000 )
printf (“The discount is %f “,sal_amt*0.07 ); /*seven percent */
else if (sal_amt = 3000 && sal_amt < 5000)
{
}
else
printf ( “ The discount is 0”) ;
Example : Determining grade category
#include<stdio.h >
#include<string.h >
main()
{
int marks;
char grade [15];
printf (“ Enter the students marks \n”);
scanf( “%d “,&marks ) ;
if ( marks > =75 && marks <=100)
{
strcpy(grade, “Distinction”); /* Copy the string to the grade */
printf(“The grade is %s” , grade);
}
else if( marks > = 60 && marks < 75 )
{
strcpy(grade, “Credit”);
printf(“The grade is % s” , grade );
}
else if(marks>=50 && marks<60)
{
strcpy(grade, “Pass”);
printf(“The grade is % s” , grade );
}
else if (marks>=0 && marks<50)
{
strcpy(grade, “Fail”);
printf (“The grade is % s” , grade) ;
}
else
printf(“The mark is impossible!” );
return 0;
}
default: (optional)
statement; (optional)
}
Note:
(i) The switch labels (case labels) must be type int (including char) constants or constant
expression.
(ii) You cannot use a variable for an expression for a label expression.
(iii) The expressions in the parenthesis should be one with an integer value. (again including type
char)
Examples:
1. A program using switch statement that prompts for entry of a number and states the number
entered.
#include<stdio.h>
main()
{
int choice;
printf(“Enter a number of your choice ”);
scanf(“ %d”, &choice);
if (choice >=1 && choice <=9) /* Range of choice values */
switch (choice)
{ /* Begin of switch* /
case 1: printf(“\n You typed 1”); break;
case 2: /* label 2* /
printf(“\n You typed 2”);
break;
case 3: /* label 3* /
printf(“\n You typed 3”);
break;
case 4: /* label 4* /
printf( “ \n You typed 4”);
break;
default:
printf(“There is no match in your choice”);
} /* End of switch*/
else
printf(“Your choice is out of range”);
return (0);
} /* End of main*/
Explanation
The expression in the parenthesis following the switch is evaluated. In the example above, it has
whatever value we entered as our choice.
Then the program scans a list of labels (case 1, case 2,…. case 4) until it finds one that matches the one
that is in parenthesis following the switch statement.
If there is no match, the program moves to the line labeled default, otherwise the program proceeds to
the statements following the switch.
The break statement causes the program to break out of the switch and skip to the next statement after
the switch. Without the break statement, every statement from the matched label to the end of the
switch will be processed.
For example if we remove all the break statements from the program and then run the program using
the number 3 we will have the following exchange.
#include <stdio.h>
main()
{
char ch;
printf(“Give me a letter of the alphabet \n”);
printf(“An animal beginning with letter”);
printf (“is displayed \n “);
scanf(“%c”, &ch);
if (ch>=’a’ && ch<=’z’) /*lowercase letters only */
switch (ch)
{ /*begin of switch*/
case `a`:
printf(“Alligator , Australian aquatic animal \n”):
break;
case ‘b’:
printf(“Barbirusa, a wild pig of Malaysia \n”);
break;
case ‘c’:
printf(“Coati, baboon like animal \n”);
break;
case ‘d’:
printf(“Desman, aquatic mole-like creature \n”);
break;
default:
printf(“ That is a stumper! \n”)
}
else
printf(“I only recognize lowercase letters.\n”);
return 0;
} /* End of main */
Like the break statement the continue statement is a jump that interrupts the flow of a program. It is
used in loops to cause the rest of an iteration to be skipped and the next iteration to be started.
Alternative 1 Alternative 2
if (a>14) if (a>14)
goto a; sheds=3;
sheds=2; else
goto b; sheds=2;
a: sheds=3; k=2*sheds;
b: k=2 * sheds;
In many programming problems a sequence of statements or in some cases the entire program may
need to be executed repeatedly a definite or indefinite number of times. The repetition or iteration
control structure is used to control this. In a finite loop the number of iterations is determined and set
by the programmer. In an infinite loop the number of repetitions is dictated by a user or other factors.
The while statement is used to carry out looping instructions where a group of instructions executed
repeatedly until some conditions are satisfied. This is a pretest loop in that the test condition is placed
before the statement block that is to be repeatedly executed. The computer evaluates the test
condition statement and as long as it returns the Boolean value of true the statement block is executed
then control returns to the test condition statement for re-evaluation. Repetition will terminate when
the test condition statement returns false.
General form:
while (expression)
statement;
The statement will be executed as long as the expression is true, the statement can be a single or
compound
/* counter.c */
/* Displays the digits 1 through 9 */
main()
{
int digit=0; /* Initialisation */
while (digit<=9)
{
printf(“%d \n”, digit);
digit++;
}
return 0;
}
Algorithm:
(i) Initialise an integer count variable to 1. It will be used as a loop counter.
(ii) Assign a value of 0 to the floating-point sum.
(iii) Read in the variable for n (number of values)
(iv) Carry out the following repeatedly (as long as the count is less or equal to n).
(v) Read in a number, say x.
(vi) Add the value of x to current value of sum.
(vii) Increase the value of count by 1.
(viii) Calculate the average: Divide the value of sum by n.
(ix) Write out the calculated value of average.
Solution
(Note that using the while loop, the loop test is carried out at the beginning of each loop pass).
In this structure the test condition is placed after the block of code that is to be repeatedly executed.
The computer first executes the block of code then evaluates the test condition statement.
General form:
do
statement;
while(expression);
The statement (simple or compound) will be executed repeatedly as long as the value of the expression
is true. (i.e. non zero).
Notice that since the test comes at the end, the loop body (statement) must be executed at least once.
Rewriting the program that counts from 0 to 9, using the do while loop:
/* counter1.c */
/* Displays the digits 1 through 9 */
main()
{
int digit=0; /* Initialisation */
do
{
printf(“%d \n”, digit);
digit++;
} while (digit<=9);
return 0;
}
Exercise: Rewrite the program that computes the average of n numbers using the do while
loop.
General form:
for (expression1;expression2;expression3)
statement;
where:
expression1 is used to initialize some parameter (called an index). The index controls the loop action. It
is usually an assignment operator.
expression2 is a test expression, usually comparing the initialised index in expression1 to some maximum
or minimum value.
expression3 is used to alter the value of the parameter index initially assigned by expression and
is usually a unary expression or assignment operator);
Example
0
1
2
3
4
5
Nesting statements
It is possible to embed (place one inside another) control structures, particularly the if and for
statements.
Example
if (number>6)
if (number<12)
printf(“You are very close to the target!”);
else
printf(“Sorry, you lose!”);
Revision Exercises
1. A retail shop offers discounts to its customers according to the following rules:
Purchase Amount >= Ksh. 10,000 - Give 10% discount on the amount.
Ksh. 5, 000 <= Purchase Amount < Ksh. 10,000 - Give 5% discount on the amount.
Ksh. 3, 000 <= Purchase Amount < Ksh. 5,000 - Give 3% discount on the amount.
0 > Purchase Amount < Ksh. 3,000 - Pay full amount.
1. Write a program that asks for the customer’s purchase amount, then uses if statements to
recommend the appropriate payable amount. The program should cater for negative purchase
amounts and display the payable amount in each case.
2. In what circumstance is the continue statement used in a C program?
3. Using a nested if statement, write a program that prompts the user for a number and then reports if
the number is positive, zero or negative.
4. Write a while loop that will calculate the sum of every fourth integer, beginning with the integer 3
(that is calculate the sum 3 + 7 +11 + 15 + ...) for all integers that are less than 30.