You are on page 1of 37

CHAPTER FOUR

CONTROL STATEMENTS
Introduction
A C++ control statement redirects the flow of a program in order to execute additional code. These
statements come in the form of conditionals (if-else, switch) and loops (for, while, do-while). Each of them
relies on a logical condition that evaluates to a Boolean value in order to run one piece of code over another.
4.1 Selection Statements: if and switch statements
4.1.1 THE IF STATEMENT
Normally the execution of a program flows line by line in the order in which it appears in the source code.
The if statement enables the programmer to test for a condition (such as whether two variables are equal)
and branch to different parts of the code depending on the result. The following if statement
if (x > 0.0)
cout<< "The value of x is positive";
will print out the message ` The value of x is positive' if x is positive.
The general form of the if statement is:
if (condition)
statement;
- OR -
if (condition) {
statement;
}
where condition is any valid logical expression or a Boolean expression. The statement can be a single C++
statement of any kind and must be terminated by a semi-colon. It can also be a compound statement, which
is a sequence of statements enclosed in left and right braces ({ and }) and acts as a single statement. The
closing right brace (}) is not followed by a semi-colon.
Following is the general form of a typical decision-making structure found in most of the programming
languages

Hope University College 1


Examples

1. The following if statement adds x to a variable sum if x is positive:


if (x > 0.0)
sum += x;
2. The following if statement also adds x to sum; in addition it adds 1 to a count of positive numbers
held in the variable poscount:
if (x >= 0.0) {
sum += x;
poscount++;
}
Note the use of the addition assignment operator, and of the increment operator. Note how in the second
example a compound statement has been used to carry out more than one operation if the condition is true.
If this had been written as follows:
if (x >= 0.0)
sum += x;
poscount++;
then if x was greater than zero the next statement would be executed, that is x would be added to sum.
However, the statement incrementing poscount would then be treated as the next statement in the program,

Hope University College 2


and not as part of the if statement. The effect of this would be that poscount would be incremented every
time, whether x was positive or negative.
The statements within a compound statement can be any C++ statements. In particular, another if statement
could be included. For example, to print a message if a quantity is negative, and a further message if no
overdraft has been arranged:
if ( account_balance< 0 ) {
cout<< "Your account is overdrawn. Balance "
<<account_balance<<endl;
if ( overdraft_limit == 0 )
cout<< "You have exceeded your limit. "<<endl;
}
In this case, the same effect could have been achieved using two if statements, and a more complex set of
conditions:
if ( account_balance< 0 )
cout<< "Your account is overdrawn. Balance "
<<account_balance<<endl;
if ( account_balance< 0 && overdraft_limit == 0 ) cout<< "You have
exceeded your limit. <<endl;
4.1.2 The if-else Statement
A simple if statement only allows selection of a statement (simple or compound) when a condition holds. If
there are alternative statements, some which need to be executed when the condition holds, and some which
are to be executed when the condition does not hold. This can be done with simple if statements as follows:
if (disc >= 0.0) cout<< "Roots are real";
if (disc < 0.0 )
cout<< "Roots are complex";
This technique will work so long as the statements which are executed as a result of the first if statement do
not alter the conditions under which the second if statement will be executed. C++ provides a direct means
of expressing this selection. The if-else statement specifies statements to be executed for both possible
logical values of the condition in an if statement.
The following example of an if-else statement writes out one message if the variable disc is positive and
another message if disc is negative:
if (disc >= 0.0)

Hope University College 3


cout<< "Roots are real";
else
cout<< "Roots are complex";
The general form of the if-else statement is:
if (condition)
statementT
else
statementF
If the condition is true then statementT is executed, otherwise statementF is executed. Both statementF and
statementT may be single statements or compound statements.

Fig: Flowchart if...else statement


Example 1:
Write a C++ program that accepts exam result of a student and determine his status as pass or fail based on
the following rule. If students mark is above or equal to 50, it displays “Congratulation You Passed the
Exam” and it displays “Sorry you didn’t pass the Exam”
Solution
#include<iostream>
using namespace std;
int main()
{
float result;
cout<<"Please enter your exam result: ";

Hope University College 4


cin>>result;
if(result >=50)
{
cout<<"Congratulations you passed the exam"<<endl;
}
else
{
cout<<"Sorry you failed the exam"<<endl;
}
return 0;
}
Example 2:
Write a program which prompts the number of hours worked in a week and an hourly rate of pay of
an employee and outputs the wage of the employee. The employee is paid at the normal hourly rate
for the first forty hours and subsequently at one and a half times the hourly rate for extra hours.
Solution
#include <iostream>
using namespace std;
int main()
{
const float limit = 40.0, overtime_factor = 1.5;
float hourly_rate , hours_worked, wage, overtime=0;
cout<< "Enter hours worked: ";
cin>>hours_worked;
cout<< "Enter hourly_rate: ";
cin>>hourly_rate;
if (hours_worked<= limit)
{
wage = hours_worked * hourly_rate;
}
else
{

Hope University College 5


overtime=hours_worked - limit;

wage = (limit* hourly_rate) +( overtime *


overtime_factor);
}
cout<< "Your Wage for " << limit<<" normal hours and with
"<<overtime<<" extra hours at "
<<hourly_rate<< " birr per hour rate is " << wage <<endl;
return 0;
}
4.1.3 if-else-if ladder statements
The if-else statement allows a choice to be made between two possible alternatives. Sometimes a choice
must be made between more than two possibilities.
Example 3:
The sign function in mathematics returns -1 if the argument is less than zero, returns +1 if the argument is
greater than zero and returns zero if the argument is zero. The following C++ statement implements this
function
#include <iostream>
using namespace std;
int main()
{
int x;
cout<<"Enter any integer: ";
cin>> x;
if (x < 0)
cout<<”-1 ";
else if (x == 0)
cout<<”+1";
else
cout<<”0";
return 0;
}

Hope University College 6


This is an if-else statement in which the statement following the else is itself an if-else statement. If x is less
than zero then sign is set to negative, however if it is not less than zero the statement following the else is
executed. In that case if x is equal to zero then sign is set to zero and otherwise it is set to positive.
Novice programmers often use a sequence of if statements rather than use a nested if-else statement. That
is, they write the above in the logically equivalent form:
if (x < 0) sign = -1;
if (x == 0) sign = 0;
if (x > 0) sign = 1;
This version is not recommended since it does not make it clear that only one of the assignment statements
will be executed for a given value of x. Also it is inefficient since all three conditions are always tested.
If nesting is carried out to too deep a level and indenting is not consistent then deeply nested if or if-else
statements can be confusing to read and interpret. It is important to note that an else always belongs to the
closest if without an else.
When writing nested if-else statements to choose between several alternatives use some consistent layout
such as the following:
if ( condition1)
statement1;
else if ( condition2)
statement2;
.
.
.
else if ( condition-n)
statement-n;
else
statement-e;

Hope University College 7


Fig: for Flow Chart if…else if in ladder
4.1.4 Nested if structure
It is always legal to nest if-else statements, which means you can use one if or else if statement inside
another if or else if statement(s).
The syntax for a nested if statement is as follows −
if( boolean_expression 1) {
// Executes when the boolean expression 1 is true
if(boolean_expression 2) {
// Executes when the boolean expression 2 is true
}
}
You can nest if...else in the similar way as you have nested if statement.

Hope University College 8


Fig: Flow chart of the general structure of Nested if statement
Example 4:
Nested if statement
#include<iostream>
usingnamespace std;
int main (){
int a =100;
int b =200;
if( a ==100)
{
if( b ==200)
{
cout<<"Value of a is 100 and b is 200"<<endl;
}
}
cout<<"Exact value of a is : "<< a <<endl;

Hope University College 9


cout<<"Exact value of b is : "<< b <<endl;
return0;
}

When the above code is compiled and executed, it produces the


following result −
Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200
Exercise
1. Write a C++ program that checks whether an integer entered from user of the program is even or odd.
2. Write a C++ program that determines age group of a person given her age based on the following rule.
Age Group
<=18 Child
<=35 Young
>35 Adult
3. Write a C++ program that accepts three integers X, Y and Z and determine the largest of all.
4. Write a C++ program that solves a quadratic equation ax2 +bx +c=0
5. Calculate the net salary of an employee given her Gross salary and her employment type.
Gross Salary Income Tax Bonus
Employment Type
Permanent Contractual
0-150 0 500
2 months’ salary

151-600 10% 550


600-1200 15% 600
1200-2600 20% 700
2600-5000 30% 800
>5000 35% 1000

Pension= 10% of G. Salary only for permanent staff


Net Salary= Gross Salary –Income Tax –Pension + Bonus

Hope University College 10


6. Write a C++ program that calculate the grade of a student using its total mark based on the following
rule.
Mark Range Grade
[85,100] A
[80,85) A-
[77, 80) B+
[70,75) B
[66,70) B-
[60,66) C+
[50,60) C
[47,50) C-
[40,47) D
[36,40) D-
[0,36) F
Otherwise Invalid Mark Message

4.1.5 THE SWITCH STATEMENT


In the last paragraphs it was shown how a choice could be made from more than two possibilities by using
nested if-else statements. However, a less unwieldy method in some cases is to use a switch statement.
The general form of a switch statement is:
switch (selector )
{
case label1:
statement1;
break;
case label2:
statement2;
break;
.
.
.
case labeln:
statementn;
break;
default:
statementd; // optional

Hope University College 11


break;
}
The selector may be an integer or character variable or an expression that evaluates to an integer or a
character. The selector is evaluated and the value compared with each of the case labels. The case labels
must have the same type as the selector and they must all be different. If a match is found between the
selector and one of the case labels, say labeli , then the statements from the statement statementi until the
next break statement will be executed. If the value of the selector cannot be matched with any of the case
labels then the statement associated with default is executed. The default is optional but it should only be
left out if it is certain that the selector will always take the value of one of the case labels. Note that the
statement associated with a case label can be a single statement or a sequence of statements (without being
enclosed in curly brackets)
The following rules apply to a switch statement −
✓ The expression used in a switch statement must have an integral or enumerated type, or be of a
class type in which the class has a single conversion function to an integral or enumerated type.
✓ You can have any number of case statements within a switch. Each case is followed by the value to
be compared to and a colon.
✓ The constant-expression for a case must be the same data type as the variable in the switch, and it
must be a constant or a literal.
✓ When the variable being switched on is equal to a case, the statements following that case will
execute until a break statement is reached.
✓ When a break statement is reached, the switch terminates, and the flow of control jumps to the next
line following the switch statement.
✓ Not every case needs to contain a break. If no break appears, the flow of control will fall
through to subsequent cases until a break is reached.
✓ A switch statement can have an optional default case, which must appear at the end of the switch.
The default case can be used for performing a task when none of the cases is true. No break is
needed in the default case.

Hope University College 12


Fig: Flow Chart of Switch statement
Example 1.
The following program prompts you to enter an integer between 1 and 7 and tells you the name of the day
corresponding to the number with an assumption that Sunday is the first day. If you enter a number out of
the range for instance 8, the program executes the default section and produce an invalid day number.
#include<iostream>
using namespace std;
int main( ){
int day;
cout<<” Enter an integer between 1
and 7 and let me tell you the day
that correspond the
number”<<endl;
cin>>day;
switch (day){
case 1 :

Hope University College 13


cout<< "The day is Sunday";
break;
case 2 :
cout<< "The day is Monday";
break;
case 3 :
cout<< "The day is Tuesday";
break;
case 4 :
cout<< "The day is Wednesday";
break;
case 5 :
cout<< "The day is Thursday";
break;
case 6 :
cout<< "The day is Friday";
break;
case 7 :
cout<< "The day is Saturday";
break;
default :
cout<< "Not an allowable day number";
break;
}
return 0;
}
Example 2:
We can modify the above program to produce an output whether the day is a weekday or weekend depending
on the day number. As follows
#include<iostream>
using namespace std;
int main( )

Hope University College 14


{
int day;
cout<<” Enter an integer between 1 and 7 and let me tell you the day
that correspond the number”<<endl;
cin>>day;
switch (day) {
case 1 :
case 7 :
cout<< "This is a weekend day";
break;
case 2 :
case 3 :
case 4 :
case 5 :
case 6 :
cout<< "This is a weekday";
break;
default :
cout<< "Not a legal day";
break;
}
return 0;
}
Therfore, if you enter 5 it will display This is a week day rather than displaying Thursday. In the same
manner if you enter 7 it will display This is a weekend instead of Sunday
Remember that missing out a break statement causes control to fall through to the next case label -- this is
why for each of the days 2-6 `This is a weekday' will be output. Switches can always be replaced by nested
if-else statements, but in some cases this may be clumsier.
Example 3:
The following example demonstrate switch statement. The program determines a student’s achievement in
words based on her grade.
#include<iostream>

Hope University College 15


Using namespace std;
int main (){
// local variable declaration:
char grade;
cout<<” Enter Your Grade”<<endl;
cin>>grade;
switch(grade){
case 'A':
cout<<"Excellent!"<<endl;
break;
case 'B':
case 'C':
cout<<"Well done"<<endl;
break;
case 'D':
cout<<"You passed"<<endl;
break;
case 'F':
cout<<"Better try again"<<endl;
break;
default:
cout<<"Invalid grade"<<endl;
}
cout<<"Your grade is "<< grade <<endl;
return0;
}
For example if you enter B or C the program dispalys“ Well done” “your grade is B/C” and if you enter
F it displays “Better try again” “your grade is F” . But if you enter anything other than A,B,C,D and F it
will execute the statement under the default section. For instance if you entered a , b, c, d, f or H, T, Z, etcit
will display invalid gradeyour grade is “ “.
Exercise

Hope University College 16


Write a C++ program that calculates the grade of a student using its total mark based on the following rule.
Implement it using switch

Mark Range Grade


[80,100] A
[70,80) B
[60, 70) C
[50,60) D
[0,50) F
Otherwise Invalid Mark Message

Summary: Syntax of Decision-Making statements

Hope University College 17


Remark: All switch statements can be converted into if … else statements. if … else statements can be
converted to switch statements if the condition is based on one variable and the number of cases are
limited.
.
4.2.LOOPING STATEMENTS (WHILE, DO…WHILE, FOR)
Loops have as objective to repeat a statement a certain number of times or while a condition is fulfilled.There
may be a situation, when you need to execute a block of code several number of times. In general, statements
are executed sequentially: The first statement in a function is executed first, followed by the second, and so
on.Programming languages provide various control structures that allow for more complicated execution
paths.
A loop statement allows us to execute a statement or group of statements multiple times and following is
the general from of a loop statement in most of the programming languages −
C++ programming language provides the following type of loops to handle looping requirements.

Sr.No Loop Type & Description

1 while loop: Repeats a statement or group of statements while a given condition is true. It
tests the condition before executing the loop body.

2 for loop: Execute a sequence of statements multiple times and abbreviates the code that
manages the loop variable.

3 do...while loop: Like a ‘while’ statement, except that it tests the condition at the end of the
loop body.

4 nested loops: You can use one or more loop inside any another ‘while’, ‘for’ or ‘do..while’
loop.

The Infinite Loop


A loop becomes infinite loop if a condition never becomes false. An infinite loop executes statements
inside the loop indefinitely. You can only terminate an infinite loop by pressing Ctrl + C keys. We will see
examples in the next sections of the module.
A. while loop

Hope University College 18


A while loop causes the program to repeat a sequence of statements as long as the starting condition remains
true. while loops are used in situations where we do not know the exact number of iterations of loop
beforehand. The loop execution is terminated on the basis of test condition.
Syntax:
We have already stated that a loop is mainly consisted of three statements – initialization expression, test
expression, update expression.
initialization expression;
while (test_expression)
{
// statements
update_expression;
}

Flow Chart for while loop


Example 1:

Hope University College 19


The following piece of C++ illustrates a while statement. It takes a value entered by the user and as long as
the user enters positive values it accumulates their sum. When the user enters a negative value the execution
of the while statement is terminated.
sum = 0;
cin>> x;
while (x > 0) {
sum += x;
cin>> x;
}
The variable sum which is to hold the accumulated sum is initialized to zero. Then a value for x is entered
so that x has a value before being tested in the condition x > 0. Note that the value of x is updated in the
body of the while loop before returning to test the condition x > 0 again.
Guideline for while loop
✓ It must be possible to evaluate the condition on the first entry to the while statement. Thus all variables
etc. used in the condition must have been given values before the while statement is executed. In the
above example the variable x was given a value by entering a value from the user.
✓ At least one of the variables referenced in the condition must be changed in value in the statement
that constitutes the body of the loop. Otherwise there would be no way of changing the truth value
of the condition, which would mean that the loop would become an infinite loop once it had been
entered. In the above example x was given a new value inside the body of the while statement by
entering the next value from the user.
✓ The condition is evaluated before the statement is executed. Thus if the condition is initially false
then the statement is never executed. In the above example if the user entered a negative number
initially then no execution of the body of the while loop would take place.
Example 2: Printing integers
The following while statement prints out the numbers 1 to 10, each on a new line.
int i; i = 1;
while (i<= 10) {
cout<<i<<endl;
i++;
}

Hope University College 20


Example 3: The following program displays hello world five times
#include <iostream>
using namespace std;
intmain()
{
// initialization expression
inti = 1;
// test expression
while(i< 6)
{
cout<< "Hello World\n";
// update expression
i++;
}
return 0;
}

Example 4: Summing Arithmetic Progression


The following portion of C++ program uses a while statement to produce the sum 1+2+3+ ...+n, where a value
for n is entered by the user. It assumes that integer variables i, n and sum have been declared:
int sum = 0, i = 1, n;
cout<< "Enter a value for n: ";
cin>> n;
while (i<= n)
{
sum += i;
i++;
}
cout<< "The sum of the first " << n << "
numbers is " << sum <<endl;
There are several important points to note here:

Hope University College 21


1. The condition i<= n requires that i and n must have values before the while loop is executed. Hence the
initialization of i to 1 and the entry of a value for n before the while statement.
2. It is possible that a while loop may not be executed at all. For example if the user entered a value 0
for n then the condition i<= n would be false initially and the statement part of the while loop would
never be entered.
3. When accumulating the sum of a sequence the variable in which we accumulate the sum must be
initialized to zero before commencing the summation. Note also that if the user entered a value for
n that was less than 1 then the initialisation of sum would mean that the program would return zero as
the accumulated total -- if n is zero this is certainly a sensible value.
Example 5: while loop: Average, Minimum and Maximum Calculation
A user is to enter positive float values from the keyboard when prompted by the program. To signal end of
input the user enters a negative integer. When data entry has terminated the program should output the
minimum value entered, the maximum value entered and the average of the positive values entered. If
there is no data entry (the user enters a negative number initially) then the program should output a
message indicating that no data has been entered.
The final version of the algorithm was:
set sum to zero. set count to zero. enter first value.
set minimum and maximum to first value.
while (value is positive)
{
add value to sum.
add one to count.
if value is bigger than maximum then set maximum to value.
if value is smaller than minimum then set minimum to value.
read a value.
}
if count is zero then output `no data entry'
else { set average to sum/count.
output count, average, maximum and minimum. }
The above algorithm can be written in C++ as follows:
// Reads in positive data until a negative number
// is entered and calculates the average and the

Hope University College 22


// maximum and minimum of the positive entries.
#include <iostream>
using namespace std;
int main() {
float value, sum, average, minimum, maximum;
int count;
sum = 0.0; count = 0; // initialise
cout<< "Enter a value: ";
cin>> value; minimum = value; maximum = value;
while (value >= 0.0) {
// process value
sum += value; // sum=sum+value
count++;
if (value > maximum) maximum = value;
if (value < minimum) minimum = value;
// get next value
cout<< "Enter a value: "; cin>> value;
}
if (count == 0)
cout<< "No data entry" <<endl;
else {
average = sum / count;
cout<< "There were " << count << " numbers" <<endl;
cout<< "Average was " << average <<endl;
cout<< "Minimum was " << minimum <<endl;
cout<< "Maximum was " << maximum <<endl;
}
return 0;
}
Exercises: use while loop to implement the following programs
1. Write a C++ program that displays the sum of all even integers between 1 and 100.

Hope University College 23


2. Write a C++ program for the following problem: A set of numbers is to be entered to the computer
and the number of negative and the number of positive values entered are to be output. All the
numbers lie between -100.0 and 100.0. The program should terminate and produce the output when
a number out of the range is entered by the user.
3. Write a C++ program that accepts 20 integers and display the number of even and odd integers
among the list of numbers it accepts.
B. THE DO-WHILE STATEMENT
It is possible that the body of a while loop will never execute. The while statement checks its condition
before executing any of its statements, and, if the condition evaluates to false, the entire body of the while
loop is skipped. However, the do ... while loop executes the body of the loop before testing its condition.
This action ensures that the body always executes at least one time.
Remark :
use do ... while when you want to ensure that the loop is execute at least once. Use
the while loopwhen you want to skip the loop if the condition is false.

Syntax:
initialization expression;
do {
// statements
update_expression;
} while (test_expression);
Note: Notice the semi – colon(“;”) in the end of loop.

Hope University College 24


diagram of
Fig: Flow do…while loop
Example 1: The following example is a version using a do-while statement of the problem considered at the
beginning of the Lesson on the while statement. The program has to accept positive numbers entered by a
user and to accumulate their sum, terminating when a negative value is entered.
sum = 0.0;
cin>> x; do { sum += x; cin>> x;
} while (x > 0.0);
Again the accumulator variable sum is initialized to zero and the first value is entered from the user before
the do-while statement is entered for the first time. The statement between the do and the while is then
executed before the condition x > 0.0 is tested. This of course is different from the while statement in which
the condition is tested before the statement is executed. This means that the compound statement between the
do and the while would be executed at leastonce, even if the user entered a negative value initially. This
value would then be added to sum and the computer would await entry of another value from the user! Thus
do-while statements are not used where there is a possibility that the statement inside the loop should not
be executed.
Example 2 : Sum of Arithmetic Progression
The following loop produces the sum 1+2+3+ ...+n, where a value for n is entered by the user:
int sum = 0; i = 1, n;
cout<< "Enter a value for n: ";
cin>> n;

Hope University College 25


do
{
sum += i;
i++;
} while (i<= n);
If the user entered a value of 0 for n then the value of 1 would be returned as the value of sum. This is obviously
incorrect and, as noted above, is because the loop statement of a do-while loop is always executed at least once.
In this case if the entered value of n is zero then the loop statement should not be entered at all! Thus if there
is any possibility that some valid data may require that a loop be executed zero times then a while statement
should be used rather than a do-while statement.
Example 3: Valid Input Checking
The do-while statement is useful for checking that input from a user lies in a valid range and repeatedly
requesting input until it is within range. This is illustrated in the following portion of C++ program:
char accept; // indicates if value in range float x; // value
entered float floatlow, high; // bounds for x
// assume low and high have suitable values
do {
cout<< "Enter a value (" << low <<" to "
<< high << "):"; cin>> x;
if (low <= x && x <= high) accept = 'y'; else
accept = 'n';
} while (accept == 'n');
Example 4: The following program to illustrate do-while loop and produces hello world only once.

#include <iostream>
using namespace std;
int main()
{
int i = 2; // Initialization expression
do
{
// loop body

Hope University College 26


printf( "Hello World\n");
// update expression
i++;
} while (i< 1); // test expression
return 0;
}
Exercises
1. What is the major difference between a while statement and a do-while statement?
2. What would be output by the following segment of C++?
int i; i = -12;
do {
cout<<i<<endl; i --; } while (i> 0)
3. Write a C++ program to implement the following requirement:
A set of examination marks expressed as percentages are to be processed by computer. Data entry is
terminated by entering a negative percentage value. As each examination mark is entered it should
be validated as being either a valid percentage or as being a negative number. The program should
ask for the data entry to be repeated until a valid value is entered. The program should then output
the number of percentage marks entered, the average mark and how many marks were above 40
The program should implement the loop by using a do-while loop.
C. THE FOR STATEMENT
Frequently in programming it is necessary to execute a statement a fixed number of times or as a control
variable takes a sequence of values.
For example consider the following use of a while statement to output the numbers 1 to 10. In this case the
integer variable i is used to control the number of times the loop is executed.
i = 1; while (i<= 10) {
cout<<i<<endl; i++;
}
In such a while loop three processes may be distinguished:
1. Initialization - initialize the control variable i (i = 1).
2. Test expression - evaluate the truth value of an expression (i<= 10).
3. Update expression - update the value of the control variable before executing the loop again (i++).

Hope University College 27


These concepts are used in the for statement which is designed for the case where a loop is to be executed
starting from an initial value of some control variable and looping until the control variable satisfies some
condition, meanwhile updating the value of the control variable each time round the loop.
Syntax:
for (initialization expr; test expr; update expr) {
// body of the loop
// statements we want to execute
}
which executes the initialize statement when the for statement is first entered, the test expression is
thenevaluated and if true the loop statement is executed followed by the update statement. The cycle of
(test; execute-statement; update) is then continued until the test expression evaluates to false, control then
passes to the next statement in the program

Fig: Flow diagram of the for loop


Example 1 : Print 10 integers. The equivalent for statement to the while statement is
for (i = 1; i<= 10; i++)
cout<<i<<endl;
which initially sets i to 1, i is then compared with 10, if it is less than or equal to 10 then the statement to
output i is executed, i is then incremented by 1 and the condition i<= 10 is again tested. Eventually i
reaches the value 10, this value is printed and i is incremented to 11. Consequently on the next test of the
condition the condition evaluates to false and hence exit is made from the loop.

Hope University College 28


Example 2: Hello world. The following program displays hello world 10 times
#include <iostream>
using name std;
int main()
{
int i=0;
for (i = 1; i<= 10; i++)
{
cout<<”Hello World";
}
return 0;
}
Output:
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World

Example 3: Student Mark Processing (3)


The previous program could also be modified to use the for statement to control the loop. This cannot be
done without changing the specification of the input data. If the specification was changed so that the number
of students was entered before the examination marks then a for statement could be used as follows:
void main() { int candno; // candidate number int s1, cw1,
s2, cw2; // candidate marks int final1, final2; // final subject marks
int count; // number of students int sum1, sum2; // sum

Hope University College 29


accumulators int subav1, subav2; // subject averages int i;
// for loop control variable
const float EXAMPC = 0.7, CWPC = 0.3; // initialise
sum1 = 0; sum2 = 0;
// enter number of students cout<< "Enter number of students: ";
cin>> count;
for (i=0; i<count; i=i+1)
{
// enter candidate number and marks cout<< "Input candidate
number and marks: "; cin>>candno>> s1 >> cw1 >> s2 >> cw2;
// process marks
final1 = int(EXAMPC*s1+CWPC*cw1); final2 =
int(EXAMPC*s2+CWPC*cw2); sum1 = sum1+final1; sum2 =
sum2+final2; // output marks cout<<candno<< " "
<< s1 << " " << cw1 << " "
<< s2 << " " << cw2 << " "
<< final1 << " " << final2
<<endl;
}
// evaluate averages subav1 = sum1/count; subav2 = sum2/count;
// output averages
cout<<endl<< "Subject1 average is " << subav1 <<endl<< "Subject2
average is " << subav2
<<endl;
}
Note that if zero or a negative number is entered for the number of students then this program will fail, an
attempted division by zero will be encountered (why?). This could be fixed by putting in a validation check
on the number of students when this is entered by the user.
Nested loops
Loops may be nested, with one loop sitting in the body of another. The inner loop will be executed in full
for every execution of the outer loop.
The following code illustrates writing marks into a matrix using nested for loops.

Hope University College 30


Illustrates nested for loops.
1: //Listing 7.14
2: //Illustrates nested for loops
3:
4: #include <iostream.h>
5:
6: int main()
7: {
8: int rows, columns;
9: char theChar;
10: cout<< "How many rows? ";
11: cin>> rows;
12: cout<< "How many columns? ";
13: cin>> columns;
14: cout<< "What character? ";
15: cin>>theChar;
16: for (int i = 0; i<rows; i++)
17: {
18: for (int j = 0; j<columns; j++)
19: cout<<theChar;
20: cout<< "\n";
21: }
22: return 0;
23: }

Output: How many rows? 4


How many columns? 12
What character? x
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxx
Analysis: The user is prompted for the number of rows and columns and for a character to print. The first for

loop, on line 16, initializes a counter (i) to 0, and then the body of the outer for loop is run.

Hope University College 31


On line 18, the first line of the body of the outer for loop, another for loop is established. A second counter
(j) is also initialized to 0, and the body of the inner for loop is executed. On line 19, the chosen character is
printed, and control returns to the header of the inner for loop. Note that the inner for loop is only one
statement (the printing of the character). The condition is tested (j < columns) and if it evaluates true, j is
incremented and the next character is printed. This continues until j equals the number of columns.
Once the inner for loop fails its test, in this case after 12 Xs are printed, execution falls through to line 20,
and a new line is printed. The outer for loop now returns to its header, where its condition (i< rows) is tested.
If this evaluates true, i is incremented and the body of the loop is executed.
In the second iteration of the outer for loop, the inner for loop is started over. Thus, j is reinitialized to 0 and
the entire inner loop is run again.
The important idea here is that by using a nested loop, the inner loop is executed for each iteration of the
outer loop. Thus the character is printed columns times for each row.
N.B. It is also possible to nest while loops, do..while loops, and you can also mix two of the three loops or
three of the three loops according to your problem.
Exercises
1. Write a for statement to output the numbers 1 to 20, each on a new line.
2. Write a segment of C++ using a for statement which accepts n real values entered by a user and
outputs their average value. Assume n will be greater than zero. Write a segment of C++ which
enters a value for ,n 0and outputs the value of . Use a while statement first, then repeat using
a do-while statement and finally repeat using a for statement.
Summary of Syntax of loops

Hope University College 32


4.3 OTHER STATEMENTS (break, continue, exit, goto, return)
a. The break statements
The break statement can be used to exit a loop statement or switch case. When the break statement is
executed, the loop or switch case statement ends immediately and execution continues with statement
following the loop or switch statement. Here is an example of a break statement:
//sums the list of 10 negative numbers
#include<iostream.h>
void main()
{
int number, sum=0, count=0;
cout<<"Enter 10 negative numbers:\n";
while(++count <=10 ) {
cin>>number;
if (number>=0) {
cout<<"ERROR: positive number"<<" or zero is entered as the \n"
<<count<<"th number! Input ends "
<<"with the "<<count << "th number.\n" <<count<<"th
number was not added in.\n";

Hope University College 33


break;
}
sum = sum + number;
}
cout<<sum<<" is the sum of the first "
<<(count-1)<<" numbers. \n";
}

Sample dialogue/run
Enter 10 negative
-1 -2 -3 4 -5 -6 -7 -8 -9 -10
ERROR: positive number or zero was entered as the
4th number! Input ends with the 4th number.
4th number was not added in
-6 is the sum of the first 3 number

b. The continue statement


The continue statement also alters the flow of control within a while, do..while, or for statement. It's effect
is to skip all the statements after the continue and return to the top of the loop. If a continue is executed
inside a for statement, the increment expression is executed before return to the top of the for loop. Here is
an example which demonstrates the continue and break statements:
//demonstrates break and continue
#include<iostream.h> void main()
{
unsigned short small, unsigned long large, skip, target; const
unsigned short MAXSMALL=65535; cout<<"Enter a small number: ";
cin>>small;
cout<<"Enter a large number: "; cin>>large;
cout<<"Enter a skip number: "; cin>>skip;
cout<<"Enter a target number: "; cin>>target; cout<<"\n";
//set up 3 stop conditions for the loop

Hope University College 34


while (small < large && large > 0 && small < MAXSMALL) { small++;
if(small % skip = = 0) //skip the decrement?
{
cout<<"Skipping on "<<small<<endl; continue; } if (large = =
target) //exact much for the target?
{
cout<<"Target reached!"; break; }
large=2;
} //end of while loop
cout<<"\nSmall: "<<small << " large " << large <<endl;
}
Sample dialog
Enter a small number: 2
Enter a large number: 20 Enter a skip number: 4
Enter a target number: 6
Skipping on 4
Skipping on 8 Small: 10 Large :8

Analysis: In the play shown in the output the user lost; small became larger than the large before the target
number of 6 was reached
c. The exit statement
The exit statement is written
exit(integer_value);
when the exit statement is executed, the program ends immediately. Any integer value may be used, but
by convention, 1 is used for a call to exit that is caused an error, and 0 is used in other cases. The exit
statement is a call to the function exit, which is in the library with header file named stdlib.h. Therefore
any program that uses the exit statement must contain the following include directive:
#include<stdlib.h>
d. The goto statement:
The goto statement in C/C++ also referred to as unconditional jump statement can be used to jump from
one point to another within a function.

Hope University College 35


Syntax:
Syntax1 | Syntax2
----------------------------
goto label; | label:
. | .
. | .
. | .
label: | goto label;
In the above syntax, the first line tells the compiler to go to or jump to the statement marked as a label.
Here label is a user-defined identifier which indicates the target statement. The statement immediately
followed after ‘label:’ is the destination statement. The ‘label:’ can also appear before the ‘goto
label;’statement in the above syntax.

Fig goto statement


Example: Demonstration of goto statement
/ C program to print numbers
// from 1 to 10 using goto statement
#include <stdio.h>

// function to print numbers from 1 to 10


void printNumbers()
{
int n = 1;
label:

Hope University College 36


printf("%d ",n);
n++;
if (n <= 10)
goto label;
}
// Driver program to test above function
int main() {
printNumbers();
return 0;
}

Output:1 2 3 4 5 6 7 8 9 10

e. The return statement


The return in C or C++ returns the flow of the execution to the function from where it is called. This
statement does not mandatorily need any conditional statements. As soon as the statement is executed, the
flow of the program stops immediately and return the control from where it was called. The return
statement may or may not return anything for a void function, but for a non-void function, a return value
is must be returned.
Syntax:
return(expression);

Remark: return statement is used mainly in functions which will be discussed and demonstrated in a
lesson which is part the next chapter.

Hope University College 37

You might also like