while loop in C++
Its function is simply to repeat statement while expression is true.
Syntax:
For example, we
are going to make a program to count down using a while loop:
// custom countdown using while
#include <iostream.h>
int main ()
{
int n;
cout << "Enter the starting number > ";
cin >> n;
while (n>0) {
cout << n << ", ";
--n;
}
cout << "FIRE!";
return 0;
}
Output:
Enter the starting number > 8
8, 7, 6, 5, 4, 3, 2, 1, FIRE!
8, 7, 6, 5, 4, 3, 2, 1, FIRE!
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:
o
true: execute statement (step 3,)
o
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).
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.
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.
No comments:
Post a Comment