C++ - Display Numbers using for loop, while loop and do while loop
The main difference between for loop, while loop, and do while loop is
- While loop checks for the condition first. so it may not even enter into the loop, if the condition is false.
- do while loop, execute the statements in the loop first before checks for the condition. At least one iteration takes places, even if the condition is false.
- for loop is similar to while loop except that
- initialization statement, usually the counter variable initialization
- a statement that will be executed after each and every iteration in the loop, usually counter variable increment or decrement.
The following sample code that can display numbers explains all 3 different loops:
Source Code
int main()
{
int num = 0;
std::cout << "Using while loop\n";
while(1)
{
std::cout << ++num << "\n";
if(num >= 5)
break;
}
std::cout << "Using do while loop\n";
num = 0;
do
{
std::cout << ++num << "\n";
} while(num < 5);
std::cout << "Using for loop\n";
for(num = 1; num <= 5; num++)
{
std::cout << num << "\n";
};
return 0;
}
Output
Using while loop
1
2
3
4
5
Using do while loop
1
2
3
4
5
Using for loop
1
2
3
4
5
Press any key to continue . . .
|