30 Sep C++ Loops
C++ loops execute a block of code and this code executes while the condition is true. Here are the types of loops in C++,
- while loop
- do…while loop
- for loop
Note: Learn how to run your first C++ program in Turbo C++. We will be running the following programs in the same way.
C++ while loop
In the while loop, the block of code executes only when the condition is true. It executes as long as the condition is true.
Here’s the syntax,
1 2 3 4 |
while (condition is true) statement; |
Here’s an example,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream.h> #include <conio.h> void main () { int x = 0; while( x < 5 ) { cout << "x = " << x << "\n"; x++; } getch(); } |
Here’s the output,
C++ do…while loop
In the do…while loop, the condition is checked at the bottom of the loop. Therefore, the loop executes at least once.
Here’s the syntax:
1 2 3 4 5 |
do{ statement; } while(condition); |
Here’s an example,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream.h> #include <conio.h> void main () { int x = 5; do { cout << "x = " << x << endl; x++; }while( x <= 10 ); getch(); } |
Here’s the output,
C++ for loop
The for loop is used when you can set how many times a statement is to be executed.
Here’s the syntax,
1 2 3 4 5 |
for (initialization; condition; increment) { statement; } |
Here’s an example,
Here you can see iterations from x = 5 to x = 10,
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream.h> #include <conio.h> void main () { for( int x = 5; x <= 10; x++) { cout << "x = " << x << "\n"; } getch(); } |
Here’s the output,
No Comments