Chapter 4
3 Loops and Decisions
A program usually is not limited to linear sequences of instructions; there may be repeating of code or the
program might take decisions. For that purpose, C++ provides control structures that serve to specify
what has to be done.
With the introduction of control structures, we introduce a new concept which is the compound statement
or block. A block is a group of statements separated with semicolons (;) but grouped together in a block
of enclosed braces.
{statement 1; statement 2; statement 3;}
Control statements require a generic statement as part of its syntax. These generic statements can be a
single statement or a compound statement (several statements/ instructions grouped in block).
3.1Loops
Loops cause a section of your program to be repeated a certain number of times. The repetition continues
while a certain condition or test expression is true. When the condition becomes false, the loop ends and
the control passes to the statements following the loop.
For all the three loops, if there is only one statement in the loop body, the brace may be omitted.
3.1.1 The for loop
The for loop executes a section of codes for a fixed number of times.
Syntax:
For (initialization; condition; increase)
{ // encloses the body of the loop
statement 1; // beginning of the body of the loop
statement 2;…
} // end of for loop
There are procedures for the execution of the for loop
1. First initialization is executed. Generally it is the initial value setting for a counter variable. This
is executed only once.
2. Next condition is checked. If it is true, the loop continues. Otherwise, the loop ends and the body
of the loop is skipped.
3. The statements in the body of the loop are executed. As usual, it can be either a single statement
or a block enclosed in braces.
4. Finally, whatever is specified in the increase field is executed and the loop gets back to step 2.
Example program: count down using for loop
// for loop.cpp
// count down
#include<iostream>
int main()
{
for (int n=10; n>0; n--)
{
cout<<n<<”,”;
}
cout<<”START!\n”;
return 0;
}
Output 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, start!
The initialization and increase fields are optional. They can remain empty but in all cases the semicolon
signs between them must be written.
Eg.for (; n<10;)
Optionally, using the comma operator(,), we can specify more than one expression in any of the fields
included in a for loop like in initialization.
Eg.for (n=0, i=100; n!=i; n++, i--)
Where n=0 and i=100 are initialization, n!=i is condition ,and n++ and i--are increase.
Figure 3.1 operation of the for loop
3.1.2The while loop
We use this loop if we don’t know how many times we won’t to do something before we start the loop.
Example program
// count down using a while loop
#include<iostream>
int main()
{
int n;
cout<<”Enter the starting number: ”;
cin>>n;
while (n>o)
{
cout<<n<<”,”;
--n;
}
cout<<”FIRE!\n”;
return 0;}
When the program starts the user is prompted to insert a starting number for the countdown. Then the
while loop begins, if the value entered by the user fulfills the condition n>0 (that n is greater than zero)
the block that follows the condition will be executed and repeated while the condition (n>0) remains
being true.
The whole process of the previous program can be interpreted according to the following script
(beginning in main):
1. User assigns a value to n
2. The while condition is checked (n>0). At this point there are two possibilities:
* condition is true: statement is executed (to step 3)
* condition is false: ignore statement and continue after it (to step 5)
3. Execute statement:
cout<< n << ", ";
4. --n;
5. (prints the value of n on the screen and decreases n by 1)
6. End of block. Return automatically to step 2
7. Continue the program right after the block: print FIRE! and end program.
The while loop looks like a simplified version of the for loop. It contains a test expression but no
initialization or increment expressions.
As long as the test expression holds true, the while loop executes until the test fails. Therefore, when
creating a while loop, we must provide a block which at some point will have false condition. Otherwise,
the loop will continue forever
Figure 3.2 operation of while loop
3.1.3 The do-while loop
One of the difference between the while loop and the do-while loop is that the do-while loop does at least
one iteration, even if the test expression is false before terminating the loop.
Eg.
int x=1;
while (x<0)
cout<<x<<endl;
At this point, there will not be any output since x>0. But if we do this example using do-while loop, we
will get one output. That is because the do-while loop does not evaluate the expression x<0 until the end
of one iteration. Each repetition is called an iteration.
int x=1;
do
cout<<x<<endl;
while(x<0);
So we should use the do-while loop, if we won’t to make sure the loop executes at least once.
// demonstrate do loop
#include<iostream>
using namespace std;
int main()
{
long dividend, divisor;
char ch;
do // start of do loop
{ // do some processing
cout<<"Enter dividend: "; cin>> dividend;
cout<<"Enter divisor: "; cin>> divisor;
cout<<"Quotient is"<<dividend/divisor;
cout<<". remainder is"<< dividend%divisor;
cout<<"\n Do another? (y/n)";
cin>>ch;
}
while (ch!= 'n'); // loop condition
return 0;
}
Possible output: Enter dividend 6
Enter divisor 3
Quotient is 2. Remainder is0
Do another(y/n)
The loop continues until you enter n.
N.B. The while statement looks much like the one in a while loop, except for its position at the end of the
loop and the fact that it ends with a semicolon.
Figure 3.3 Operation of the do loop
3.2 Decisions
Decisions always relate to the same question: should we do this? Programs also need to make these
onetime decisions. In a program, a decision causes a one time jump to a different part of the program
depending on the value of the expression.
3.2.1 Condition structure: if and else
If keyword is used to execute a statement or block only if a condition is fulfilled.
Syntax
If (condition) statement;
or if (condition)
{
statement 1;
statement 2;…
}
where condition is the expression that is being evaluated. If this condition is true, statement or block
containing statements is executed. If it is false, statements ignored (not executed) and the program
continues right after this conditional structure.
Eg.if (x == 100)
cout<< “x is 100”;
Or if (x == 100)
{
cout<< “x is”;
cout<< x;
}
Example program:
// if demo. Cpp demonstrates checks whether a number is greater than 100 or not
// demonstrates if statement
# include <iostream>
int main ()
{
int x;
cout<< “ enter a number:”;
cin>> x;
if (x > 100)
cout<< “the number is greater than 100 \n”;
return 0;
}
We can additionally specify what we want to happen if the condition is not fulfilled by using the keyword
else.
Syntax:
if (condition) if (condition)
statement 1; {
else or statement 1;
statement 2; }
else
{
statement 2;
}
Eg.if (x==100)
cout<<”x is 100”;
else
cout<<”x is not 100”
if + else structures can be concentrated in a nested if from with the intention of verifying more than two
possible conditions.
Example
// nested if and checks a number for positive, negative or zero
#include<iostream>
int main()
{
int x;
cout<<”Enter a number”;
cin>>x;
if (x>0)
cout<<”\n x is positive”;
else if (x<0)
cout<<”\n x is negative”;
else
cout<<”\n x is zero”;
return 0;
}
It must be noted that if more than one statement is to be executed in each of the conditions, the statements
under each condition must be enclosed in braces {}.
Figure 3.4 Operation of the if – else statement
3.2.2 The Conditional Operator
The conditional operator is powerful and unique. It provides a shorthand method of expressing a simple
if/else statement. The operator consists of the question-mark (?) and the colon(:).
Its format is
expression ?expression : expression;
Here is an example of a statement using the conditional operator:
x< 0 ? y = 10 : z = 20;
This statement is called a conditional expression and consists of three sub-expressions separated by the ?
and : symbols. The expressions are x < 0, y = 10, and z = 20. Since it takes three operands, the conditional
operator is considered a ternary operator.
The conditional expression above performs the same operation as the following if/else statement:
if (x < 0)
y = 10;
else
z = 20;
The part of the conditional expression that comes before the question mark is the expression to be tested.
It’s like the expression in the parentheses of an if statement. If the expression is true, the part of the
statement between the ?and the : is executed. Otherwise, the part after the : is executed.
If it helps, you can put parentheses around the sub-expressions, as shown here:
(x< 0) ? (y = 10) : (z = 20);
// Example compares two numbers and asigns the maximum to another variable
#include<iostream>
using namespace std;
int main()
{int a,b,max;
a=9,b=5;
max=(a>b)?a:b;
cout<<max;
return 0}
output: 9
3.3 Other Control Statement
3.3.1Jump Statements
3.3.1.1The break statement
Using break, we can leave a loop even if the condition for its end is not fulfilled. It can be used to end an
infinite loop, or to force it to end before its natural end. An infinite loop is a loop that has no end or is a
loop that functions forever or till something quits the program. The next statement after the break is
executed, is the statement following the loop. For example, we are going to stop the count down before its
natural end:
Example programs:
//break loop example
#include<iostream>
int main()
{
int n;
for(n=10; n>0; n--)
{
cout<<n<<”,”;
if (n==3)
{
cout<<”countdown aborted!”;
break;
}
}
return 0;
}
Output 10, 9, 8, 7, 6, 5, 4, 3, countdown aborted!
Figure 3.5 operation of the break statement
3.3.1.2 The continue statement
The break statement takes you out of the bottom of a loop. Sometimes, however, you want to go back to
the top of the loop when something unexpected happens. Executing continue has this effect.
The continue statement causes the program to skip the rest of the loop in the current iteration as if the end
of the statement block had been reached, causing it to jump to the start of the following iteration.
For example, we are going to skip the number 5 in our countdown:
Example program:
//continue loop example
//makes the loop display the number
#include<iostream>
int main()
{
for(int n=10; n>0; n--)
{
if(n==5)continue;
cout<<n<<”,”;
}
cout<<”FIRE!\n”;
return 0;
}
Output 10, 9, 8, 7, 6, 4, 3, 2, 1, FIRE
Figure 3.6 opreation of continue statment
3.3.2The Switch Statement
If you have a large decision tree and all the decision depend on the value of the same variable, you will
probably want to consider a switch statement instead of a ladder of if…else or else if constructions. Its
objective is to check several possible constant values for an expression. Something similar to what we did
at the beginning of this section with the concatenation of several if and else if instructions. The syntax of
the switch statement:
switch (expression)
{
case constant 1;
group of statements 1;
break;
case constant 2;
group of statements 2;
break; …
default;
default group of statements;
}
It works in the following way: switch evaluates expression and checks if it is equivalent to constant 1, if it
is, it executes group of statements 1 until it finds the break statement. When it finds this break statement
the program jumps to the end of the switch selective structure.
If expression was not equal to constant 1 it will be checked against constant2. If it is equal to this, it will
execute a group of statements 2 until a break keyword is found, and then will jump to the end if the
switch selective structure.
Finally, if the value of expression did not match any of the previously specified constants (you can
include as many case labels as values you want to check), the program will execute the statements include
after the default: label, if it exists(since it is optional).
Example:
switch(x)
{
case 1:
cout<<”x is 1”;
break;
case 2:
cout<<”x is 2”;
break;
default:
cout<<”value of x is unknown”;
}
switch example if-else equivalent
switch (x) { if (x == 1) {
case 1: cout << "x is 1";
cout << "x is 1"; }
break; else if (x == 2) {
case 2:
cout << "x is 2";
cout << "x is 2";
}
break;
else {
default:
cout << "value of x unknown";
cout << "value of x unknown";
}
}
Figure3.7 operation of the switch statement
Notice that switch can only be used to compare an expression against constants. Therefore, we cannot put
variables as labels (for example case n: where n is a variable) or ranges (case (1…3):) because they are
not valid C++ constants