[go: up one dir, main page]

0% found this document useful (0 votes)
18 views20 pages

Unit Four- Control Structures

Unit Four covers control structures in programming, detailing their execution order and types: sequence, selection, and iteration. It explains the use of if-else statements, conditional operators, and switch-case for selection, as well as while, do-while, and for loops for iteration. Additionally, it discusses break and continue statements to alter control flow within loops.

Uploaded by

antomotongori
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)
18 views20 pages

Unit Four- Control Structures

Unit Four covers control structures in programming, detailing their execution order and types: sequence, selection, and iteration. It explains the use of if-else statements, conditional operators, and switch-case for selection, as well as while, do-while, and for loops for iteration. Additionally, it discusses break and continue statements to alter control flow within loops.

Uploaded by

antomotongori
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/ 20

UNIT FOUR: CONTROL STRUCTURES

Control structure refers to the order in which the individual statements, instructions, or function
calls of an imperative or functional program are executed or evaluated. Control structures serve
to specify what has to be done by the program, when and under which circumstances.

There are three main types of control structures: A computer program can be executed:

In sequence
Selectively (branch) - making a choice
Repetitively (iteratively) - looping
4.1 Sequence
Statements execute one after the other in the order in which they are written—that is,
in sequence

Example
#include<iostream>
using namespace std;
int main(){

double a, b;
cout<<”enter a number:”;
cin>>a;

1
b=a+a;

cout<< “The sum of the numbers is % d:” ,b);


return 0;}

4.2 Selection

In selection control structures, conditional statements are features of a programming language


which perform different computations or actions depending on whether a programmer- specified
Boolean condition evaluates to true or false.
The basic attribute of a selection control structure is to be able to select between two or more
alternate paths.

Uses i) if..else

ii) conditional operator

iii) switch statement

i) if..else

It is used to execute an instruction or block of instructions only if a condition is fulfilled. Its


form is:
if (condition) statement

2
where condition is the expression that is being evaluated. If this condition is true, statement is
executed. If it is false, statement is ignored (not executed) and the program continues on the next
instruction after the conditional structure.
For example, the following code fragment prints out x is 100 only if the value stored in variable x
is indeed 100:
if (x == 100)

cout << "x is 100";

If we want more than a single instruction to be executed in case that condition is true we can
specify a block of instructions using curly brackets { }:
if (x == 100)

cout << "x is ";


cout << x;
}

We can additionally specify what we want to happen if the condition is not fulfilled by using
the keyword else. Its form used in conjunction with if is:
if (condition) statement1 else statement2

For example:

if (x == 100)

cout << "x is 100";


else
cout << "x is not 100";
prints out on the screen x is 100 if indeed x is worth 100, but if it is not -and only if not- it prints
out x is not 100.
The if .. else structure can be concatenated with the intention of verifying a range of values. The
following example shows its use telling if the present value stored in x is positive, negative or
none of the previous, that is to say, equal to zero.
if (x > 0)S

cout << "x is positive";


else if (x < 0)

3
cout << "x is negative";
else
cout << "x is 0";

Remember that in case we want more than a single instruction to be executed, we must group
them in a block of instructions by using curly brackets { }.
Example

Write a C++ program that requests a user to input the name of a student and marks scored in a
subject. Use if…else statement to print A for exam grades greater than or equal to 90, B for
grades in the range 80 to 89, C for grades in the range 70 to 79, D for grades in the range 60 to
69 and F for all other grades:
#include<iostream>
#include<string>

using namespace std;


int main(){
string name;

int mark;

cout<<"Please enter student name:";


cin>>name;
cout<<"Please enter student Score:";
cin>> mark;
if ( mark >= 90 ) // 90 and above gets "A" cout <<
"Grade is :A\n";
else if ( mark >= 80 ) // 80-89 gets "B" cout <<
"Grade is :B\n";
else if ( mark >= 70 ) // 70-79 gets "C" cout <<
"Grade is :C\n";
else if ( mark >= 60 ) // 60-69 gets "D" cout <<
"Grade is :D\n";
else // less than 60 gets "F"
cout << "Grade is :F\n";
return 0;
4
}

Example 2

Write a program that requests user to input a number between 1-7 and displays the corresponding
day of the week.
#include<iostream>
#include<string>
using namespace std;
int main(){
int day;
cout<<"Please enter the number of the weekday 1-7:";
cin>>day;

if ( day== 1)

cout << "The weekday is Sunday\n";


else if ( day== 2 )
cout << "The weekday is Tuesday\n";
else if ( day== 3 )
cout << "The weekday is Wednesday\n";
else if ( day== 4)
cout << "The weekday is Thursday\n";
else if( day== 5)
cout << "The weekday is Friday\n";
else if ( day== 6)
cout << "The weekday is Saturday\n";
else
cout << "The weekday is Sunday\n";
return 0;}

5
ii) Conditional operator

C++ provides the conditional operator (?:) which is closely related to the if…else
statement. The conditional operator is C’s only ternary operator—it takes three
operands.
The operands together with the conditional operator form a conditional expression.
The first operand is a condition.
The second operand is the value for the entire conditional expression if the condition is true and
the third operand is the value for the entire conditional expression if the condition is false.
Example

Cout<<”%s\n",grade>=60? "Passed" : "Failed" );

Contains a conditional expression that evaluates to the string literal "Passed" if the condition
grade >= 60 is true and evaluates to the string literal "Failed" if the condition is false.
The second and third operands in a conditional expression can also be actions to be
executed.
Example

grade>=60?cout<<"Passed\n": cout<<"Failed\n" ;

is read, “If grade is greater than or equal to 60 then cout<<"Passed\n", otherwise cout<<
"Failed\n" .”

iii) Switch Case statement

Switch structure is the alternate to if-else. The switch expression is evaluated first and the value
of the expression determines which corresponding action is taken. Convenient when there are
multiple cases to choose from.
Syntax for using switch statement:
switch(variable)

case 1:

statements1;
break;

case n:

6
statementsn;
break;

default:

statements;
break;}

Example

Write a program that requests user to input a number between 1-7 and displays the corresponding
day of the week using switch..case.
#include<iostream>
using namespace std;
int main(){
int day;
cout<<"\tDAY OF WEEK DETAILS:\n";

cout<<"\t \n";

cout<<"Please enter the number of the weekday 1-7:";


cin>>day;

switch(day){

case 1:cout << "\nThe weekday is Sunday"; break;

case 2:cout << "\nThe weekday is Monday"; break;


case 3:cout << "\nThe weekday is Tuesday"; break;
case 4:cout << "\nThe weekday is Wednesday"; break;
case 5:cout << "\nThe weekday is Thursday"; break;
case 6:cout << "\nThe weekday is Friday"; break; case
7:cout << "\nThe weekday is Saturday"; break;
default:cout << "\n You have entered a wrong choice";
}
return 0;

}
7
Example 3

Write a program that requests for input of a grade letter. The program should then display
the appropriate grade entered. Use switch..case
#include <iostream>
using namespace std;
int main()
{
char grade;

cout << "Enter your grade: "; cin >> grade; cout << endl;
switch (grade)
{

case 'A':cout << "Your grade is A. Distinction" << endl; break;

case 'B':cout << "Your grade is B: Credit" << endl; break;


case 'C':cout << "Your grade is C: Pass" << endl;break;
case 'F':
case 'f':cout << "Your grade is F: Fail." << endl; break;
default:

cout<<" The grade is invalid."<<endl;

return 0;

8
Exercise

1. Write a C++ program that prompts for input of three numbers. Using if ..else, the
program should determine which number is the largest.
2. Write a program that checks whether a number is odd or even and gives appropriate
message.
3. Write a program that displays the following options for the user and requests user to
make a choice.
Please pick an option from the following:"
a) Talk
b) Eat
c) Play
d) Sleep

Depending on the user's choice, it should switch between the different cases. The appropriate
message is then output using the 'cout' command.
Choice Message
1 You chose to talk...talking too much is a bad habit.
2 You chose to eat...eating healthy foodstuff is good.
3 You chose to play...playing too much every day is bad.
4 You chose to sleep...sleeping enough is a good habit
Any other You did not choose anything...so exit this program
number
4. Using the switch..case statement, write a program that generates a simple calculator.
The program should prompt user to input two values and then input an arithmetic
operator (eg +, -, *,/). The program should then calculate and display output. Eg 3+4=7

9
4.3 Iteration/Repetition

Statements are executed zero or more times, until some condition is met.
Repetition allows you to efficiently use variables
They can be divided into:

a) While
b) Do while
c) For Loop

i) While loop
 Repeats statement while the condition set in expression is true. Statement
continues to execute until the expression is no longer true

10
 The general form of the while statement is:

while (expression)
statement

Infinite loop: a loop that continues to execute endlessly. Can be avoided by including
statements in the loop body that assure exit condition will eventually be false
Example

11
Example 2

Using the while loop, write a program that asks user to enter radius and then calculates the area
of a circle using the formula A=PI*radius *radius. Take Pi=3.14. The program should terminate
when user enters zero (0).
#include <iostream>
using namespace std;
int main()
{
int radius, area;

//double area;

const double pi=3.14;

cout << "Enter your radius (to terminate enter 0): ";
cin >> radius; cout << endl;
while (radius!=0)
{
area=pi*radius*radius;
cout << "The area is "<<area<<endl;
cout << "Enter your radius (to terminate enter 0): "; cin >> radius; cout << endl;
}
return 0;
}

12
ii) Do while loop

Its functionality is exactly the same as the while loop, except that condition in the do-while
loop is evaluated after the execution of statement instead of before, granting at least one
execution of statement even if condition is never fulfilled.
The general form of a do...while statement is:

do

statement
while
(condition);
The statement executes first, and then the expression is evaluated. If the expression evaluates
to true, the statement executes again.
As long as the expression in a do...while statement is true, the statement
executes The following is a flow chart for the do-while loop

13
Example

Example comparison between while v do while

iii) For loop

for repetition statement, which specifies the counter-controlled repetition details in a single
line of code.

The general form of the for statement is

14
for ( initialization; Condition; increment/decrement )

{statements}

The three parts are:

 Initialization: sets a loop control variable to an initial value.


 Condition: is an expression that is tested each time the loop repeats. As long as
condition is true (nonzero), the loop keeps running.
 Increment/decrement: is an expression that determines how the loop control
variable is incremented each time the loop repeats.
Example

1. //program prints numbers 1-to


10 #include <iostream>
using namespace
std; int main(){
for(int i=1; i<=10; i++){
cout<<i<<<< " "<<endl;
}
return 0;

}
2. The factorial (!) is the product of all integers less than or equal to n but greater than or
equal to 1. The following program computes both the summation and the factorial of the
numbers 1 through 15:
//Declare loop control variable inside the
for #include <iostream>
using namespace std;

int sum=0;
int fact=1;

15
// compute the factorial of the numbers through
15 for (int i=1; i<=15; i++){
sum +=i;
fact *=i;
}

cout<<"The sum is :"


<<sum<<endl; cout<<"Factorial
is :"<< fact;
return 0;
}

3. Program requests user to enter number of rows and prints the following pyramid.

#include
<iostream> using
namespace std; int
main()
{
int rows;
cout << "Enter number of rows:
"; cin >> rows;
for(int i = 1; i <= rows; ++i)
{
for(int j = 1; j <= i; ++j)
{
cout << j << " ";
}
cout << "\n";
}

16
return 0;
}

Example: Program to print full pyramid using *

#include <iostream>
using namespace
std; int main()
{

int space, rows;

cout <<"Enter number of rows:


"; cin >> rows;
for(int i = 1, k = 0; i <= rows; ++i, k = 0)
{

for(space = 1; space <= rows-i; ++space)

cout <<" ";

while(k != 2*i-1)

cout << "* ";

++k;

17
}

cout << endl;

return 0;

}
4.4 Break & continue Statements

Break and continue alter the flow of control. When the break statement executes in a
repetition structure, it immediately exits.
The break statement, in a switch structure, provides an immediate
exit The break statement can be used in while, for, and do...while
loops The break statement serves two purposes:
 To exit early from a loop
 To skip the remainder of the switch structure

After the break statement executes, the program continues with the first statement after the
structure. The use of a break statement in a loop can eliminate the use of certain (flag) variables
Continue is used in while, for, and do…while structures. When executed in a loop, it skips
remaining statements and proceeds with the next iteration of the loop

// break statement exiting a for


statement. #include <iostream>
using namespace
std; int main()
{

int count; // control variable also used after loop


terminates for ( count = 1; count <= 10; ++count ) //
loop 10 times
{
cout << count << " "; } // end for

18
cout << "\nBroke out of loop at count = " << count << endl;

} // end main

// break statement exiting a for statement. #include <iostream>

using namespace std; int main()

int count; // control variable also used after loop terminates for ( count = 1; count <= 10; ++count
) // loop 10 times

cout << count << " ";

} // end for

cout << "\nBroke out of loop at count = " << count << endl;

} // end main

Exercises

1. Factors of a number are numbers that, when multiplied you get another number. For
instance, factors of 15 are 3 and 5; factors of 10 are 2 and 5, etc. Write a program using C++
language that uses a nested for loop to find the factors of the numbers from 2 to 100;

2. Write a program that checks whether a number is odd or even for numbers from 1-100 and
outputs the message “Odd” or “even “as appropriate. The program should not have user input.

3. Write a program that sums up odd numbers between 1 and 90. The program should not
have user input.

4. Write a program that calculates the area of a circle or rectangle or triangle depending on
user choice. Use do…while and case statement.

19
5. Fibonacci series refers to a series of numbers in which each number is the sum of the two
preceding numbers. For example 1, 1, 2, 3, 5, 8, 13, 21, 34, 55… etc. Write a program using a
while loop to calculate and display the first n fibonacci numbers.

6. A company pays its salespeople on a commission basis. The salespeople receive Ksh. 200
per week plus 9 percent of their gross sales for that week. For example, a salesperson who sells
Ksh. 5000 worth of chemicals in a week receives Ksh. 200 plus 9 percent of Ksh. 5000, or a total
of Ksh. 650. Develop a C++ program that will input each salesperson's gross sales for last week
and calculate and display that salesperson's earnings. Process one salesperson's figures at a time

20

You might also like