0% found this document useful (0 votes)
4 views

Lecture 5 - Control Structures

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Lecture 5 - Control Structures

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

LECTURE 5 - CONTROL STRUCTURES

Introduction

Control structures represent the forms by which statements in a program are executed.

Three structures control program execution:


• Sequence
• Selection or decision structure
• Iteration or looping structure

Sequence Control Structure


This is the simplest control structure. It dictates the order of execution from one statement to the next
within the program. In the absence of repetition or branching, the program instructions will be
executed in the order in which they were coded.

Basically, program statements are executed in the sequence in which they appear in the program.

Decision/Selection Control Structure


The structure is used for decision making within a program. It allows alternative actions to be taken
according to conditions that exist at particular stages within a 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:

if (score >= 50)


printf(“Pass”);
else
printf(“Fail”);

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”);

(ii) if (salary >500)


Tax_amount = salary * 1.5;

(iii) if(balance<1000 || status =’R’)


print (“Balance = %f”, balance);

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.

Note: Indentation is not required but it is a standard style of programming.

Example:
if(x >=0)
{
printf(“let us increment x:\n”);
x++;
}
else
printf(“x < 0 \n”);

Multiple Choice: else if (Nested IF)


This is a control structure that is used when more than two choices have to be made. It involves having
IF structure inside another IF structure either in the true or false part.

The general form is:

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)
{

Disc = sal_amt * 0.05; /* five percent */


printf ( “ The discount is %f “ , Disc ) ;

}
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;
}

The ‘switch’ and ‘break’ statements


The switch - break statements can be used in place of the if - else statements when there are several
choices to be made. The switch structure is used to test if a variable equals some constant values then
executes the equivalent statement.

The structure of a switch is as follows:

switch (integer expression)


{
case constant 1:
statement; optional
case constant 2:
statement; optional
…………

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.

Example: Demonstrating the ‘switch’ structure

#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.

Enter a number of your choice 3


You typed 3
You typed 4
There is no match in your choice

Example: Demonstrating the ‘switch’ structure

#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 */

The ‘continue’ statement

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.

If a break is used in a loop it quits the entire loop.

The ‘goto’ statement


It takes the form goto labelname;
Example
goto part2;
part2: printf(“programming in c”\n”;)
In principle you never need to use goto in a C statement. The if construct can be used in its place as
shown below.

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;

Looping/Repetition Control Structure

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.

C supports three loop versions:


• while loop
• do while loop
• for loop.

The ‘while’ loop

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;
}

Example: Calculating the average of n numbers using a ‘while’ loop

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

/* To add numbers and compute the average */


#include<stdio.h>
main()
{
int n, count = 1;
float x, average, sum=0.0;
/* initialise and read in a value of n */
printf(“How many numbers? “);
scanf(“%d”, &n);

/*Read in the number */


while (count<=n)
{
printf(“x = “);
scanf(“%f”, &x);
sum+=x;
count++;
}
/* Calculate the average and display the answer */
average = sum/n;
printf(“\n The average is %f \n”, average);
return 0;
}

(Note that using the while loop, the loop test is carried out at the beginning of each loop pass).

The ‘do .. While’ loop (Post-Test)

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.

The ‘for’ loop

This is the most commonly used looping statement in C.

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

for (int k=0; k<=5; k++)


printf(k = %d \n”, k);
Output

0
1
2
3
4
5

Example: Counting 0 to 9 using a ‘for’ loop

/* Displays the digits 1 through 9 */


#include<stdio.h>
main()
{
int digit;
for(digit=0;digit<=9; digit++)
printf(“%d \n” , digit);
return 0;
}

Example: Averaging a set of numbers using a ‘for’ loop


/* average.c */
/* To add numbers and compute the average */
#include<stdio.h>
main()
{
int n, count;
float x, average, sum=0.0;.

/* initialise and read in a value of n */


printf(“How many numbers? “);
scanf(“%d”, &n);
/*Read in the number */
for(count=1;count<=n;count++)
{
printf(“x = “);
scanf(“%f”, &x);
sum+=x;
}
/* Calculate the average and display the answer */
average = sum/n;
printf(“\n The average is %f \n”, average);
return 0;
}

Example: Table of cubes

/ Using a loop to make a table of cubes */


#include<stdio.h>
main()
{
int number;
printf(“n n cubed “);
for(num=1; num<=6;num++)
printf(“%5d %5d \n”, num, num*num*num);
return 0;
}
Also note the following points about the for structure.
• You can count down using the decrement operator
• You can count by any number you wish; two’s threes, etc.
• You can test some condition other than the number of operators.
• A quantity can increase geometrically instead of arithmetically.

Nesting statements
It is possible to embed (place one inside another) control structures, particularly the if and for
statements.

Nested ‘if’ statement


It is used whenever choosing a particular selection leads to an additional choice

Example

if (number>6)
if (number<12)
printf(“You are very close to the target!”);
else
printf(“Sorry, you lose!”);

Nested ‘for’ statement


Suppose we want to calculate the average of several consecutive lists of numbers, if we know in
advance how many lists are to be averaged.

Example: Nested ‘for’ statements


/* Calculate the averages of several different lists of number */
#include<stdio.h>
main()
{
int n, count, loops, loopcount;
float x, average, sum;
/*Read in the number of loops */
printf(“How many lists? “);
scanf(“%d”, &loops);
/*Outer loop processes each list of numbers */
for (loopcount=1; loopcount<=loops; loopcount++)
{
/* initialise sum and read in a value of n */
sum=0.0;
printf(“List number %d \n How many numbers ? “,loopcount);
scanf(“%d”, &n);
/*Read in the numbers */
for(count=1;count<=n; count++)
{
printf(“x = “);
scanf(“%f”, &x);
sum+=x;
} /* End of inner loop */
/* Calculate the average and display the answer */
average = sum/n;
printf(“\n The average is %f \n”, average);
} /*End of outer loop */
return 0;
}

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.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy