6.5 while Statement

I l @ ve RuBoard

The while statement is used when the program needs to perform repetitive tasks . The general form of a while statement is:

 while (   condition   )   statement   ; 

The program repeatedly executes the statement inside the while until the condition becomes false (0). (If the condition is initially false, the statement will not be executed.)

For example, Example 6-2 computes all the Fibonacci numbers that are less than 100. The Fibonacci sequence is:

1 1 2 3 5 8 . . .

The terms are computed from the equations:

1
1
2 = 1 + 1
3 = 2 + 1
5 = 3 + 2

etc.

In general, the Fibonacci sequence is defined as:

f n = f n - 1 + f n - 2

This is a mathematical equation using math-style variable names (f n ). Mathematicians use this very terse style of naming variables , but in programming, terse is dangerous, so we translate these names into something verbose for C++:

Mathematician

Programmer

f n

next_number

f n-1

current_number

f n-2

old_number

So in C++ code, the equation is expressed as:

 next_number = current_number + old_number; 

We want to loop until our current term is 100 or larger. The following while loop will repeat our computation until we reach this limit.:

 while (current_number < 100) 

In our while loop we compute the value of current_number . Next we need to advance one term.

This completes the body of the loop. The first two terms of the Fibonacci sequence are 1 and 1. We initialize our first two terms to these values.

Figure 6-1 shows what happens to the variables during the execution of the program.

Figure 6-1. Fibonacci execution
figs/c++2_0601.gif

At the beginning, current_number and old_number are 1. We print the value of the current term. Then the variable next_number is computed (value 2). Next we advance one term by putting current_number into old_number and putting next_number into current_number . This is repeated until we compute the last term and the while loop exits. Example 6-1 shows our algorithm written as C++ code.

Example 6-1. fib/fib.cpp
 #include <iostream> int   old_number;     // previous Fibonacci number int   current_number; // current Fibonacci number  int   next_number;    // next number in the series int main(  ) {     // start things out      old_number = 1;     current_number = 1;     std::cout << "1\n"; // Print first number     while (current_number < 100) {         std::cout << current_number << '\n';         next_number = current_number + old_number;         old_number = current_number;         current_number = next_number;     }     return (0); } 
I l @ ve RuBoard


Practical C++ Programming
Practical C Programming, 3rd Edition
ISBN: 1565923065
EAN: 2147483647
Year: 2003
Pages: 364

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net