C++ while loop – C# Programming Example
General

C++ while loop

Its format is:

 
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:

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:

(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.

We must consider that the loop has to end at some point, therefore, within the block of instructions (loop’s statement) we must provide some method that forces condition to become false at some moment, otherwise the loop will continue looping forever. In this case we have included --n; that causes the condition to become false after some loop repetitions: when n becomes 0, that is where our countdown ends.

Of course this is such a simple action for our computer that the whole countdown is performed instantly without practical delay between numbers.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: