Wednesday, 11 June 2014
9.2 The while Statement
When we do not know the exact number of loop repetitions before the loop execution begins, then we use while loop control statement. For example, we may wish to continue writing cheques as long as our bank balance is above Tshs 250,000.00. Figure 5 is a flow chart for a while control statem
Figure 4 shows the flow of control for a simple while statement. So long as x is less than y, the program continues to execute the while loop. With each pass through the loop, however, x is incremented by one. When it is no longer less than y, control flows to the next statement. Note that the while loop is sometimes called the while do loop
Examples on while loop
Example 9.10
The program to displays the string “Hello World” five times using the while loop.
/* Demonstration of while loop */
#include <iostream.h>
main()
{
int c = 0;
while (c <= 4)
{
cout <<”\nHello World”;
c++;
}
count <<”\nDone”;
}
Example 9.11
A program segment that computes and displays gross pay for seven employees. The loop body (the steps that are repeated) is the compound statements that start on the seventh line i.e. after the statement while (c <= 4). The loop body gets an employee’s payroll data and computes and displays pay. After seven pay amounts are displayed the last statement calls the cout function to display the message:
/* Demonstration of a while loop */
#include <iostream.h>
main()
{
int count_emp;
double hours, rate, pay;
count_emp = 0;
/* test value of count_emp */
while (count_emp < 7)
{
count << “\nHours”;
cin >> hours;
cout << “/nRate”;
cin >> rate;
pay = hours * rate;
cout << “pay is Tsh. “ << pay << endl;
/* increment count_emp */
Count_emp = count_emp + 1;
}
cout << ”\nAll employees processed”;
}
Running the program, the output becomes:
All employees processed
Example 9.12
In the following program, the while loop is used to calculate the factorial of a number. In this program, the number is received from the keyboard using the cin function and is assigned to the variable “number”. The variable “factorial” is declared as long int to hold the expected large number and is initialized with the value “1”. The final value of the factorial is reached through the iterative process:
/* Calculation of factorial */
#include <iostream.h>
main()
{
int number;
long int factorial = 1;
cout << ”\nEnter the number:”;
cin >> number;
while(number > 1)
factorial = factorial * number-- ;
cout <<”\nThe factorial is “ << factorial;
}
Note:
factorial = factorial * number--;
This statement is equivalent to two statements:
factorial = factorial * number;
number = number -1;
9.3 The do . . . while Loop
One important characteristic to the while statement is that the test condition is at the top of the loop. This means that if the condition is false (or zero) the first time, the while body will never be executed. But there are certain situations where you need to execute the body at least once. These situations are not common, but when they do occur, you should use the do while statement.
The only difference between a do while and a regular while loop is that the test condition is at the bottom of the loop. This means that the program always executes the compound statement at least once (the first time through). Then, depending on the value of expression, it may loop back to do, or it may continue with the next statement.
Example 9.13
The following program uses the do while statement to print the statement Hello World four times. Compare this program with the while loop program in example 1 above.
/* Demonstration of do while statement */
#include <iostream.h>
main()
{
int c = 0;
do {
cout << ”\nHello World”;
c++;
} while (c <= 4);
cout << ”\nDone”;
}
Example 9.14
The following program uses the do while statement to compute the factorial of a number. Compare this program with the while loop program in example 3 above.
/* Calculation of factorial using do while loop */
#include <iostream.h>
main()
{
int number; long int factorial;
factorial = 1;
count << ”\nEnter the number:”;
cin >> number;
do {
factorial = factorial * number--;
} while (number > 1);
cout << ”\nThe factorial is “ << factorial;
}
9.4 The for Statement
C++ provides the for statement as another form for accomplishing loops. The for loop statement is used to repeat a statement or block of statements a specified number of times. The general form of the for loop is:
for (initialization; test expression; increment expression)
body of the loop
The parentheses following the keyword for contain what we call as the loop expression. The loop expression is divided by semicolons into three separate expressions: the “initialize expression” (or initialization), the “test expression,” and the “increment expression.”
The Initialize Expression
The initialize expression, initializes the variable and it is always executed as soon as the loop is entered.
Typical example of a loop expression is like:
for (number = 0; number < 10; number++ )
cout << “\n number = “ << number;
The initialize expression, number = 0, initializes a variable number to 0. The test expression, number < 10, test the loop variable. Each time through the loop to see if number is less then 10. If the test expression is true, (i.e. number < 10), the loop will be executed. If the expression becomes false (number is 10 or more), the loop will be terminated and control will pass to the statements following the loop.
The increment expression, number++, increments the variable number each time the loop is executed. To do this, it uses the increment operator (++), described earlier. Note that the loop variable in a for loop does not have to be increased by 1, or changed by some other number, using an expression such as:
number = number + 3;
The Body of the Loop, this is a statement or statements that follow the keyword for and the loop expression: They are executed each time round the loop. In the typical example above, there is only one statement:
cout << “\n number = “ << number;
Note that this statement is terminated with a semicolon, whereas the for with the loop expression is not. This is because the entire combination of the for keyword, the loop expression, and the statement constituting the body of the loop, are considered to be a single C++ statement. Figure 6 is a flowchart that illustrate the operation of the for loop.
Example 9.15
// A program that prints numbers 0 through 9 and their total
#include <iostream.h>
main()
{
int number, total = 0
for (number = 0; number < 10; number ++)
{
total += number;
cout << “\n number << “ total = “ << total;
}
}
When this program is run, the output will be as follows
number = 0 total = 0
number = 1 total = 1
number = 2 total = 3
number = 3 total = 6
number = 4 total = 10
number = 5 total = 15
number = 6 total = 21
number = 7 total = 28
number = 8 total = 36
number = 9 total = 45
9.5 Nested Loops
In programming, nesting is locating a loop within a loop. The fundamental structure of all programs is a series of loops, which are sets of instructions repeated certain number of times. When an if then or while loop is placed within the beginning and end of another loop, it is said to be nested. For example, the program to calculate the factorial of number given in Example 3 can be modified and written with nested loops as seen in Example 7 below:
Example 9.16
/* Factorial calculation using a nested loop */
#include <iostream.h>
#include <stdlib.h>
main()
{
int number, counter; long int factorial;
for(;;)
{
factorial = 1;
cout << ”\nEnter the number: ”;
cin >> number;
if (number == 0)
exit(0);
counter = number;
do {
factorial = factorial * counter--;
} while (counter > 1);
cout <<”\nFactorial of “ << number ” = “ << factorial;
}
}
Things to note:
1. The factorial program of Example 6.16 is included into an infinite for loop, which ends only if you enter the number 0. In this case, the for loop is called the outer loop and the do while loop is called the inner loop.
2. The expression (;;) after the keyword for in example 7 above is used to create an infinite for loop which can be terminated by pressing the keys [ctrl] + [c] together. You can end the run of the program by entering 0.
Example 9.17
The program in Figure 6.17 demonstrates the nesting of two for loops inside each other in order to draw the graph shown in Figure 6
\* Demonstration of nested for loops */
#include <iostream.h>
main()
{
int x, y;
for (x = 1; x <= 5; ++x)
{
cout << ”\n”;
for (y = 1; y < 8; ++y)
{
cout << “$”;
}
}
}
When this program is run, the output will be as follows:
Example 9.18
Modify example 8 print asterisks as shown in figure 7 below.
Solution:
#include <iostream.h>
main()
{
int x, y;
for (x = 1; x <= 5; ++x)
{
cout << ”\n”;
for (y = 1; y <= x; ++y)
{
cout << “*”;
}
}
Example 9.19
A program to generate multiplication table using nested for loop
#include <iostream.h>
main( )
{
int cols, rows, product;
for (rows = 1; rows < 4; rows++)
{
for (cols = 1; cols < 4; cols++)
cout << cols * rows << “ “;
cout << endl;
}
}
When this program is run, the output will be as follows:
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment