0% found this document useful (0 votes)
27 views10 pages

Control Structures

The document provides an overview of control structures in programming, specifically focusing on sequence, selection, and iteration. It explains the use of if statements, switch statements, and various looping constructs such as for, while, and do...while loops, along with examples for each. Additionally, it includes programming exercises to reinforce the concepts discussed.

Uploaded by

Bethwel Kipruto
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)
27 views10 pages

Control Structures

The document provides an overview of control structures in programming, specifically focusing on sequence, selection, and iteration. It explains the use of if statements, switch statements, and various looping constructs such as for, while, and do...while loops, along with examples for each. Additionally, it includes programming exercises to reinforce the concepts discussed.

Uploaded by

Bethwel Kipruto
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/ 10

CONTROL STRUCTURES

Program control
• Specify order in which statements are to executed
• A control structure is a control statement and the statements whose execution it controls
• The following are the three control structures used to control program execution: sequence, selection and
iteration

I) SEQUENCE
Here, each statement in the program is executed once and in the same order in which they are listed.

II) SELECTION
It occurs when the program is able to evaluate conditions and select alternative courses of action. Conditions are
usually inform of expression. There are two ways in which selection may be made: -
i) if statements
ii) switch statements.

i) if statements
General format for if a statement is as follows:

if (Expression)
Statement;
else
Statement;

With else being option – single selection. If there are more than one statements in the if or else, then braces
must be used to define the scope of the statement.

Example
Write a C program that inputs three subjects marks for a student and computes the average mark. Program
displays pass if the student average mark is more than or equal to 50 and fail when the student average mark is
below 50.

# include <stdio.h>
int main ( )
{
float mark1, mark2, mark3, average;
printf("Enter the three subject marks\n");
scanf("%f%f%f", &mark1, &mark2, &mark3);
average = ( mark1+mark2+mark3)/3;
if (average > = 50)
printf ("pass\");
else
printf ("fail\n");
return 0;
}

Using if statements for multiple selections


It occurs when if…else construct is nested after else. It’s often used to test a sequence of parallel alternatives
where only one alternative is executed. It’s mostly implemented by using the else if construct

Programming Notes ~ Wainaina Page 1 of 10


General format

if (Expression)
{
Statement(s);
}
else if (Expression)
{
Statement(s) ;
}
………..
…………
else
{
Statement(s);
}

Example 1
Write a program that inputs three different integer numbers and output the largest

# include <stdio.h>
int main ( )
{
int number1, number2, number3;
printf ("Enter three integer numbers\n");
scanf ("%d%d%", &number1, &number2 ,&number3);
if (number1 > number2 && number1 > number3)
{
printf("The largest number is %d\n", number1);
}
else if ( number2 > number1 && number2 > number3)
{
printf("The largest number is %d\n", number2);
}
else
{
printf("The largest number is %d\n", number3);
}
return 0;
}

Example
Write a program that simulates a simple calculation. The program reads two numbers and a character (operator).
If the character is “+ ” then sum is displayed. If it is “–“ then difference is displayed. If it is “*” then product is
displayed. If it is “/” then quotient is displayed. Use a switch statement.

# include <stdio.h>
int main ()
{
int number1, number2, answer1;
float answer2;
char op;

Programming Notes ~ Wainaina Page 2 of 10


printf("enter the two integer numbers \n");
scanf("%d%d", &number1, &number2);
printf("enter the arithmetic of perator \n");
scanf(" %c", &op);
/* make use of the else… if construct to make decisions*/
if(op == '*')
{
answer1 = number1 * number2;
printf("%d*%d = %d\n", number1, number2, answer1);
}
else if(op == '/')
{
answer2 = (float) number1/number2;
printf ("%d/%d = %f\n", number1, number2, answer2);
}
else if(op == '+')
{
answer1 = number1 + number2;
printf("%d+%d=%d\n" ,number1, number2, answer1);
}
else if (op == '-')
{
answer1 = number1 - number2;
printf("%d - %d = %d\n", number1, number2, answer1);
}
else
printf("invalid operator \n");
return 0;
}

ii) Using switch case for multiple selection


Switch case structure is used as an alternative to the if...then...else if for selectively executing one block of
statements from among multiple blocks of statements. It generally used to make the code more readable
when there are several choices.
A switch case structure works with a single test expression that is evaluated once, at the top of the structure.
The value obtained is then compared with the values for each case in the structure. If there is a match, it
executes the block of statements associated with that case. The following is the basic format.

switch (expression or variable)


{
case value 1:
prog statement1;
prog statement2;
break;
case value 2:
prog statement3;
prog statement4;
break;
case value n:
prog statement n+1;
prog statement n+2;
break;

Programming Notes ~ Wainaina Page 3 of 10


default:
prog statement;
prog statement;
}

The following must be considered when using the case construct:


i). Values for the case must be integer or character constants.
ii). The order of the case statement is not important.
iii). All cases must be distinct.
iv). The expression in the construct is evaluated first and the result is matched with each constant present in
the cases.
v). The break statement causes an explicit exit from the switch statement.
vi). The default clause may occur first (convention places it last)

Example
Write a program that simulates a simple calculation. The program reads two numbers and a character (operator).
If the character is “+ ” then sum is displayed. If it is “–“ then difference is displayed. If it is “*” then product is
displayed. If it is “/” then quotient is displayed. Use a switch statement.

# include <stdio.h>
int main ()
{
int number1, number2, answer1, choice;
float answer2;
/* menu of operation*/
printf("1 Multiplication \n");
printf("2 Division \n");
printf("3 Addition \n");
printf("4 Subtraction \n");
/*end of menu*/
printf("Enter two integer numbers \n");
scanf("%d%d", &number1, &number2);
printf("Enter your choice\n");
scanf("%d", &choice);
switch (choice)
{
case 1:
answer1 = number1 * number2;
printf("%d*%d = %d\n", number1, number2, answer1);
break;

case 2:
answer2 = (float) number1/number2;
printf("%d/%d = %f\n", number1, number2, answer2);
break;

case 3:
answer1 = number1 + number2;
printf("%d+%d=%d\n", number1, number2, answer1);
break;

case 4:

Programming Notes ~ Wainaina Page 4 of 10


answer1 = number1 – number2
printf("%d-%d=%d\n", number1, number2, answer1);
break;

default:
printf("Invalid operators entry! \n");
}
return 0;
}

III) ITERATION
This occurs when the program is able to repeat a given task as long as the condition is true and in C is achieved
in three different ways:
i) The for loop
ii) The while loop
iii) The do…while loop
In each case, there’s a condition, which allows the loop to terminate

The for Loop


Is a looping structure that is used when the number of repetition are known in advance. This loop uses a
variable (counter) that increases or decreases in value during each repetition of the loop.
The for loop has three principle elements
i) The start condition
ii) The terminating condition
iii) The action which takes place at the end of each iteration

Syntax
for ( initialise_expr; test_expr; increment_expr )
{
statement(s);
}

Example
Write a program that generates and displays all integers numbers between 1 and 20

# include <stdio.h>
int main ( )
{
int counter;
for (counter = 1; counter <=20; counter++)
{
printf("%d\n", counter);
} /* end of loop */
return 0;
} /* end of main */

Example
Write a program that displays both the lower case and upper case alphabetical letters using the following format
Lowercase Uppercase
a A
b B
c C

Programming Notes ~ Wainaina Page 5 of 10


… …
… …
z Z

# include <stdio.h>
int main ( )
{
char letter1, letter2;
printf("Lowcase\t Uppercase\n");
for(letter1 = 'a', letter2 = 'A'; letter1<='z', letter2<='Z';
letter++, letter2++)
printf("%c\t\t %c\n", letter1,letter2);
return 0;
}

Example
Write a program that will generate and compute the sum and average of numbers 1 to 50 using a for loop. The
program displays both the sum and average on the screen.

# include <stduio.h>
int main ( )
{
int number, sum = 0;
float average;
for(number = 1; number <= 50; ++number)
{
sum +=number;
}
average=(float) sum/50;
printf("sum = %d, average = %0.2f\n", sum, average);
return 0;
}

Example
Write a program that generates and displays a 10 by 10 multiplication table
1 2 3 4…………10
2 4 6 8……………
3………………….
……
……
10……………..100

# include <stdio.h>
int main ( )
{
int i,j,table;
for(i=1; i<=10; i++)
{
for(j=1; j<=10; j++)
{
table = i*j;
printf ("%d\t", table);

Programming Notes ~ Wainaina Page 6 of 10


}
printf("\n");
}
return 0;
}

The while and do while loops


The while loop and do…while loop are very similar i.e. they execute a block of statements an indefinite number
of times, but there’s one difference between them, the while loop test for pre-condition (the condition for
executing the loop is evaluated at the beginning of each loop) in contrast to the do… while loop, which test for
post condition and hence the do… while will executes at least once, whereas the while loop may not execute at
all if the condition is already false.

The while loop.


It has the following syntax:
while (expression)
{/* while expression is true execute this block */
statement(s);
}
If there is more than one statement, then braces must be used.

The do…while loop


It has the following syntax
do
{
Statement1;
Statement2;
break;
…………..
}
while (expression);

Example
Write a program that generates and displays numbers 1 to10 using the following control structures
i) while loop
ii) do while…loop

Solution

/*Using a while loop*/


# include<stdio.h>
int main ( )
{
int counter;
counter = 1;
while(counter < =10)
{
printf("%d\n", counter);
counter++;
} /* end of while loop*/
return 0;
} /* end of main function*/

Programming Notes ~ Wainaina Page 7 of 10


/*Using a do…while loop*/
# include<stdio.h>
int main( )
{
int counter;
counter = 1;
do
{
printf("%d\n", counter);
counter ++;
}while(counter < = 10);
return 0;
} /* end of main function */

Example
Write a program that displays the following temperature conversion chart on the screen as follows below.

Hint: c = 5.0/9.0 * (f – 2)
C = degrees in Celsius
F = degree in Fahrenheit

Fahrenheit Celsius
*****************************
0 -17.68
20 -6.67
40 4.44
… …
… …
300 148.89

# include <stdio.h>
int main ( )
{
int fahrenheit = 0;
float celsius;
printf("fahrenheit \t \t celsius\n");
printf("*********************\n");
while(fahrenheit < = 300)
{
celsius = 5.0/9.0 * (fahrenheit - 32);
printf("% d \t \t % f\n", fahrenheit, celsius);
farhenheit +=20;
} /* end of while */
return 0;
} /* end of main */

Example
Write a program generates and sums all even numbers and product of all odd numbers between 20 and 50 using
a looping control structure.

# include <stdio.h>
int main ( )

Programming Notes ~ Wainaina Page 8 of 10


{
int number = 20, sum = 0, product = 1;
while(number<=50)
{
if(number%2==0)
{
sum += number;
}
if(number%2! = 0)
{
product*= number;
}
number ++;
} /* end of while */
printf("The sum of all even numbers is % d\n", sum);
printf("The product of all odd numbers is % d\n",
product);
return 0;
} /* end of main */

Example
Write a program in C that uses a loop construct to compute the squares of all even numbers that fall between 26
and 97 (inclusive). The square of a number num is computed as square=num * num. The program then
outputs the results in the format shown below

Number Square
26 676
27 784
… …
… …
#include <stdio.h>
int main ( )
{
int number, square;
number = 26;
while(number <= 97)
{
if(num%2 ==0)
{
square = number * number;
printf ("%d\t\t%d/n", number, square);
}
number ++;
}
return 0;
}

Special loop flow control


The break keyword is used to break out of the while, do ... while, switch ... case and for control.
The continue keyword is used to loop back to the while, do ... while and for control.

Programming Notes ~ Wainaina Page 9 of 10


Example
#include<stdio.h>
int main()
{
int i;
for(i=0; i<10; ++i)
{
if (i==5) { continue; }
if (i==7) { break; }
printf ("Loop number: %d \n", i);
}
return 0;
}

Exercises
1. Rewrite the following segment of code using if… else statement
switch (x)
{
case 1:
case 2:
case 3:
printf("\n x is greater than y");
break;
default:
printf("\n The value %d is out of range", x);
break;
{

2. In a certain institution, candidates are awarded order of merits as follows


4 points distinction
3 points credit
2 points pass
1 pont fail

write a C program that prompts the user for his or her points (4, 3, 2 or 1) and then displays the order of
the merit.
Hint (make use of the switch case statements)

3. Write a complete C program to calculate either the area of triangle, rectangle or circle. The program should
have a decision making statement to decide: -
i) If the figure is a triangle then ask for base/height values to input
ii) If the figure is a rectangle, then ask for length & breadth values to input
iii) If the figure is a circle then asks for radius value to input the program should display output on
the screen.

4. Write a C program that inputs a year and then it determines whether it is a leap year or not. Your program
should display an appropriate message.
Hint:
A year is a leap year if it is divisible by 400 and not by 100 or it is divisible by 4

Programming Notes ~ Wainaina Page 10 of 10

You might also like