Sometime we want to show or print on the screen some numbers that continuous regularly. For example 1, 2, 3, 4, 5, 6, 7, 8, 9, 10.
We can use cout<< syntax for each numbers.
cout<<”1, ”;
cout<<”2, ”;
cout<<”3, ”;
cout<<”4, ”;
cout<<”5, ”;
cout<<”6, ”;
cout<<”7, ”;
cout<<”8, ”;
cout<<”9, ”;
cout<<”10, ”;
But if we want to show more than 10 or more again, for example 100 or 200 or 300 or more numbers, so it will be not effective to type the syntax above. Beside it, it would be need more memory space too use to save the all variables number.
To solve the problem, we can use looping with while.
Here is the format of the syntax
While (expression) statement
while syntax will repeat the statement until the expression is false.
#include “iostream.h”
#include “conio.h”
main ()
{
int x;
cout << "Enter start number > ";
cin >> x;
while (x>0) {
cout << x << ", ";
--x;
}
cout << "STOP!";
getch();
}
See the picture as the result:
Note: --x mean that the value of the variable x, will be decrease 1 by 1 while the looping is still running.
0 comments:
Post a Comment