Last modified: Mon, 02 Nov 2009 12:53:15 +0200
Complete: ##################-- (90%)
4.1 Introduction
4.2 The while Statement
4.3 The do ... while Statement
4.4 The for Statement
4.5 Infinite Loops
4.6 The break Statement
4.7 The continue Statement
4.8 Nested Loops
4.9 Examples
4.10 Exercises
4.1 Introduction
Loops are control structures that cause a program to repeat (iterate) a block of code.
In C++ there are three basic loop statements: while, do ... while and for.
As in the other programimming languages, the infinite and nested loops are also allowed in C++.
4.2 The while Statement
A while loop causes your program to repeat a sequence of statements as long as
the starting condition remains true. Its general form is:
while (condition) {
statements
.
.
}
where condition is a valid C++ expression and statements are any executable statement.
When condition evaluates to true, the block is executed, and then condition is tested again.
This continues until the condition is false.
For example the following seciton of code
int x = 1;
while (x <= 6) {
cout << x << " " << x*x << endl;
x++;
}
will output
1 1
2 4
3 9
4 16
5 25
6 36
Program 4.1 evaluates the sum: 1 + 2 + 3 + ... + n via a while loop.
04prg01.cpp:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
|
// Example use of a while loop
#include <iostream>
using namespace std;
int main()
{
int k=0, s=0, n;
cout << "Input n: ";
cin >> n;
while (k<=n)
s += k++;
cout << "sum is " << s << endl;
return 0;
} |
Input n: 10
sum is 55
|
Note that in this example no braces follow the while statement and so only one line of code is iterated, i.e. "s += k++;".
While this is correct and concise, for clarity it can be good practice to be more explicit and include braces as follows:
while (k<=n) {
s += k++;
}
4.3 The do ... while Statement
The do ... while loop executes the body of the loop before its condition is tested.
This means the body of the loop is executed at least once. Its general form is:
do {
statements
.
.
} while (condition);
An example usage is illustrated in Program 4.2 which outputs the message Hello a number of times determined by the value of counter.
04prg02.cpp:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
|
// Example usage of the do ... while loop
#include <iostream>
using namespace std;
int main()
{
int counter;
cout << "How many hellos? ";
cin >> counter;
do {
cout << "Hello\n";
counter--;
} while(counter > 0);
cout << "counter is " << counter << endl;
return 0;
} |
How many hellos? 4
Hello
Hello
Hello
Hello
counter is 0
|
In this program, the body of the loop is executed at least once, indepenedent of the initial value of count.
4.4 The for Statement
The for statement allows you to execute a block of code a specified number of times.
The syntax for the for statement is as follows:
for ( initialization; condition ; increment ) {
statements
.
.
}
Here, the initialization statement is used to initialize the loop counter.
condition is any C++ conditional expression and is evaluated on each iteration of the loop.
If the condition is true, increment is executed, this gives the step size of the loop counter.
The block of statements is executed on every iteration of the loop.
For example, the following lines outputs Hello World ten times:
for (int i=1; i<=10; i++)
cout << "Hello World" << endl;
Note that braces are not needed in this case as there is only one line of statements to execute.
This is equivalent to
int i = 1;
while (i<=10) {
cout << "Hello World" << endl;
i++;
}
The loop counter can also be a real variable, but because of limited numerical precision of floats and doubles
the result can be undepredictable. Instead it is good practice to always use integer counters and derive reals from them,
in this way the number of iterations in the loop is well controlled.
For example, to output the values of x starting from 10 down to 1 in steps of 0.1 and the corresponding natural logarithms
we can use the following code section:
for(int i=100; i>0; i--) {
float x = i*0.1;
cout << "x = " << x << " ln(x) = " << log(x) << endl;
}
Initialization and the increment may be replaced by multiple C++ statements, each separated by a comma.
For example,
for(int i=0, j=5; i<3; i++, j--)
cout << "i j: " << i << " " << j << endl;
will be output as
i j: 0 5
i j: 1 4
i j: 2 3
i j: 3 2
In the following example, Program 4.3, n real values are input, and the sum and mean of these values are output.
In order to know how many values will be input, the user first enters the value of n.
04prg03.cpp:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
|
// Example use of the "for" loop
#include <iostream>
using namespace std;
int main()
{
int n;
float x, total=0.;
cout << "How many values will you input? ";
cin >> n;
for (int i=1; i<=n; ++i) {
cout << "Input value " << i << ": ";
cin >> x;
total += x;
}
float mean = total/n;
cout << "The sum is " << total << endl;
cout << "The mean is " << mean << endl;
return 0;
} |
How many values will you input? 5
Input value 1: 4.6
Input value 2: 5.2
Input value 3: 6.1
Input value 4: 3.6
Input value 5: 8.3
The sum is 27.8
The mean is 5.56
|
Note that counter variable i can be declared inside the for statement, consequently i is local to the
for block (which is all it needs to be).
Also note that it is important to initialize variable total with zero before it is used, otherwise the result of the program will be unpredictable.
We can be more concise by placing the increment "total += x;" inside the for statement (after the counter increment):
for (int i=1; i<=n; ++i, total += x) {
cout << "Input value " << i << ": ";
cin >> x;
}
4.5 Infinite Loops
If a loop starts its execution and the condition of a loop is always true,
then loop iterates its body infinitely. For example, consider the following two equivalent code sections:
while (true) {
cout << "I am in an infinite loop..." << endl;
}
or
while (1) {
cout << "I am in an infinite loop..." << endl;
}
Both of them will output "I am in an infinite loop..." endlessly (until the program is shut down).
Other equivalent examples are:
do
cout << "I am in an infinite loop..." << endl;
while(7>3);
for(;;)
cout << "I am in an infinite loop..." << endl;
Usually the programmer will anticipate a condition where an infinite loop can be exited,
for this C++ provides the break statement described in the following section.
4.6 The break Statement
Loops can be exited at any point by using a break statement.
For example, the following code continues to read values and outputs their reciprocal until a zero is input,
i.e. the loop terminates when a zero in input.
The break statement allows the loop to terminate part of the way through the iteration block (avoiding
an attempt to output the reciprocal of the terminating value).
do {
cout << "input x: ";
cin >> x;
if ( x==0 ) break;
cout << "its reciprocal is " << 1./x << endl;
} while(1);
cout << "loop terminated." << endl;
4.7 The continue Statement
The continue statement is similar to break, except that instead of terminating the loop,
it starts re-executing the body of the loop from the top.
For example, at the end of the following loop,
mean of the 10 numbers are calculated excluding zero and negatives.
For example Program 4.4 input ten values and outputs the mean excluding zero values.
04prg04.cpp:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
|
// Example use of a continue statement
#include <iostream>
using namespace std;
int main()
{
float sum=0., x;
int count=0;
for (int i=1; i<=10; i++) {
cout << "input number " << i << " :";
cin >> x;
if( x==0 ) continue; // jump to the top of the block
count++;
sum += x;
}
cout << count << " non-zero values were input." << endl;
cout << "Their mean is " << sum/count << endl;
} |
input number 1 :4.6
input number 2 :3.2
input number 3 :0.0
input number 4 :6.7
input number 5 :3.2
input number 6 :1.8
input number 7 :0.0
input number 8 :0.0
input number 9 :4.5
input number 10 :6.8
7 non-zero values were input.
Their mean is 4.4
|
4.8 Nested Loops
Loops may be nested, with one loop sitting in the body of another. The inner loop will be executed
fully for every execution of the outer loop.
Program 4.5 outputs integer pairs (x, y) satisfying the inequality |x| + |y| < 3. There are 13 such pairs.
04prg05.cpp:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
|
// Example use of nested loops
#include <iostream>
#include <cstdlib>
using namespace std;
/*
This program outputs (x, y) integer pairs,
satisfying the inequality |x| + |y| < 3
*/
int main() {
int c = 1, p = 2;
for (int x = -p; x <= p; x++) {
for (int y = -p; y <= p; y++) {
if( abs(x)+abs(y)<3 )
cout << c++ << " (" << x << " ," << y << ")" << endl;
}
}
return 0;
} |
1 (-2 ,0)
2 (-1 ,-1)
3 (-1 ,0)
4 (-1 ,1)
5 (0 ,-2)
6 (0 ,-1)
7 (0 ,0)
8 (0 ,1)
9 (0 ,2)
10 (1 ,-1)
11 (1 ,0)
12 (1 ,1)
13 (2 ,0)
|
Note that the header cstdlib is included for accessing the integer abs function (required for example in gcc 4.3).
4.9 Examples
Program 4.6 outputs N! (N-factorial) where N is input from the keyboard.
Note that variable factorial is declared as long in attempt to increase the range
of factorials it can manage before an integer overflow occurs.
In the case of a 64-bit platform, the largest correct computation of a factorial in this case is
20! = 2 432 902 008 176 640 000; remember that the limit for a long is 18 446 744 073 709 551 615
and so 21! will overflow. The apparently huge range of the long int is clearly still not enough for some applications.
The situation is worse for a 32-bit platform where the long int is the same as an int which can calculate
correctly only up to 12!.
04prg06.cpp:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
|
// Program to compute the factorial of a positive integer.
// It is assumed that N is positive ( N >= 0 )
#include <iostream>
using namespace std;
int main () {
unsigned int i, n;
unsigned long factorial=1;
cout << "Input N: ";
cin >> n;
for (i=2; i<=n; i++) factorial *= i;
cout << n << " N! = " << factorial << endl;
} |
Input N: 4
4 N! = 24
Input N: 9
9 N! = 362880
|
Program 4.7 performs a sequential search for roots of sine(x) over the
range 0 < x < 2 pi radians in steps of 0.0001 radians.
We know a root is present somewhere between x and x+dx
when the sign of the function changes; the best estimate
of the position is then at the center x+dx/2 and the
maximum error is dx/2 (half the step).
Note the search range is carefully formed so that it includes the limits 0 and 2 pi.
04prg07.cpp:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
|
// Sequential search for roots of sine(x)
// over the range 0 < x < 2 pi radians in steps of 0.0001 radians
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double dx=0.0001, x=-dx/2;
do {
if ( sin(x)*sin(x+dx) < 0 )
cout << "A root is found near x=" << x+dx/2 << endl;
x = x+dx;
} while (x < 2*M_PI);
} |
A root is found near x=0
A root is found near x=3.1416
A root is found near x=6.2832
|
4.10 Exercises
- How do you choose between while and do ... while?
- How do you choose between while and for?
- Is it better to use while (1) or for (;;)?
- How do I initialize more than one variable in a for loop?
- What happens if you create a loop that never ends?
- What is the output of the following program?
#include <iostream>
#include <cmath>
int main() {
double x=0.;
for (int i=1, j=1; i<=10000000; ++i, j=-j) x += j/(2.0*i-1);
std::cout << M_PI/(4*x) << std::endl;
}
- What is the output of the following program?
#include <iostream>
int main() {
int n=1;
while (true) {
for(int m=1; m<n; m++)
std::cout << m*n << ' ';
std::cout << std::endl;
if (n++>4) break;
}
}
- Rewrite the following for loop using while loop.
for (int x = 0; x < 10; x += 2) cout << '*';
- What is the value of x when the for loop completes?
for (int x = 0; x < 100; x++)
- What is the value of x when the do ... while loop completes?
int x = 10, k;
do{
k = ++x;
x -= 2;
}while(k>0);
- What is the value of t when the for loops complete?
t = 0;
for (a=1; a<=5; a+=1)
for (b=1; b<=a; b+=2)
t += a + b;
- Write a nested for loop that outputs the following 4-by-10 pattern of 0s:
0000000000
0000000000
0000000000
0000000000
- Write a program that inputs a positive integer number n and outputs the odd numbers between 1 and n.
For example, for n = 12, program should output:
1 3 5 7 9 11
- After each bounce of a ball the height of the ball is half that of its previous height.
Write a program to evaluate the height of the ball after 10 bounces, if the initial height is 4 m.
- Write a program that evaluates first 30 terms the following series:
1 + 1/2 + 1/4 + 1/8 + 1/16 + 1/32 + ...
What is the result after one million terms?
- Write a program to evaluate the first 20 terms of the following infinite series:
5/6 + 13/36 + 35/216 + 97/1296 + ...
This is a convergent series. Find the convergent value of the series analytically and compare your computer result with this value.
- Write a program that reads a positive integer, k, and outputs its proper divisors.
For example, for k = 28, the proper divisors are 1 2 4 7 14 28
- A perfect number, p, is a positive integer number whose sum of divisors excluding p itself equal to p.
For example, p = 6 is a perfect number since 6 = 1 + 2 + 3.
Write a program to list and count all perfect numbers less than 10,000.
- Write a program that reads a positive integer number m and then prints the english name of each digit
of that number in a single line.
For example, for m = 147, program should output:
one four seven
- A positive integer n > 1 is called a prime number if it has only two positive divisors (1 and n). The first few primes are:
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, ...
Write a program to list and count all prime numbers less than 10,000.
Hint: you can use the algorithm defined here: Sieve of Eratosthenes.
|