Monday, September 29, 2008

Repetitive structures or loops

Loops have as objective to repeat a statement a certain number of times or while a condition is fulfilled.

The while loop.

Its format is: while (expression) statement and its function is simply to repeat statement while expression is true.

For example, we are going to make a program to count down using a while loop:

void main ()
{
  int n;
  cout << "Enter the starting number > ";
  cin >> n;
  while (n>0) {
    cout << n << ", ";
    --n;
  }
  cout << "FIRE!";
  getch();
}

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 be greater than 0), the block of instructions that follows will execute an indefinite number of times while the condition (n>0) remains true.

All the process in the program above can be interpreted according to the following script: beginning in main:

1. User assigns a value to n.

2. The while instruction checks if (n>0). At this point there are two possibilities:

true: execute statement (step 3,)

false: jump statement. The program follows in step 5.

3. Execute statement:
cout << n << ", ";
--n;
(prints out
n on screen and decreases n by 1).

4. End of block. Return Automatically to step 2.

5. Continue the program after the block: print out FIRE! and end of program.

Source : Cplusplus.com

No comments: