Professional Documents
Culture Documents
Chapter 3
Loops and Decisions
3.1. Introduction
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.2. Loops
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 pass 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.2.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.
1
[Type text]
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>
Using namespace std;
int main()
{ Output:
for (int n=10; n>0; n--) 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, End!!
{
cout<<n<<”,”;
}
cout<<”End\n”;
return 0;
}
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.
2
[Type text]
#include <iostream>
using namespace std;
int main()
{
int j; //define a loop variable
for(j=0; j<15; j++) //loop from 0 to 14,
cout << j * j << “ ”; //displaying the square of j
return 0;
}
Here’s the output:
0 1 4 9 16 25 36 49 64 81 100 121 144 169 196
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
3
[Type text]
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 << ", ";
--n;
(prints the value of n on the screen and decreases n by 1)
4. End of block. Return automatically to step 2
5. 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.
4
[Type text]
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
iteration.
int x=1;
do
cout<<x<<endl;
while(x<0);
So we should use the do-while loop, if we want to make sure the loop executes at
least once.
// demonstrate do loop
#include<iostream>
using namespace std;
int main()
{
long dividend, divisor; Possible output:
charch; Enter dividend 6
do // start of do loop Enter divisor 3
{ // do some processing Quotient is 2.
cout<<"Enter dividend: "; Remainder is 0
cin>> dividend; Do another(y/n)
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;
}
5
[Type text]
3.3. 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 onetime jump
to a different part of the program depending on the value of the expression.
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.
6
[Type text]
Eg.
if (x == 100)
cout<< “x is 100”;
Or
if (x == 100)
{
cout<< “x is”;
cout<< x;
}
Example program:
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;
}
Example
7
[Type text]
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>
Using namespace std;
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 {}.
8
[Type text]
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);
9
[Type text]
// Example compares two numbers and assigns 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
10
[Type text]
11
[Type text]
12
[Type text]
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";
}
}
13
[Type text]
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.
14