Understanding Loops in C++
Understanding Loops in C++
1. For Loop
The for loop is used when the number of iterations is known beforehand. It consists of three
parts: initialization, condition, and increment/decrement.
Syntax:
Example:
#include <iostream>
using namespace std;
int main() {
for (int i = 0; i < 5; i++) {
cout << "Iteration: " << i << endl;
}
return 0;
}
Initialization
Condition
Increment/Decrement
Check
Execute Code
Block
2. While Loop
The while loop is used when the number of iterations is not known and depends on a
condition. The loop continues as long as the condition is true.
Syntax:
while (condition) {
// Code to be executed
}
Example:
#include <iostream>
using namespace std;
int main() {
int i = 0;
while (i < 5) {
cout << "Iteration: " << i << endl;
i++;
}
return 0;
}
The loop variable is The loop condition is The code inside the The loop variable is The loop continues
set to its initial checked for truth. loop is executed. updated. or exits based on the
value. condition.
3. Do-While Loop
The do-while loop is similar to the while loop, but it guarantees that the code block is
executed at least once, as the condition is checked after the execution.
Syntax:
do {
// Code to be executed
} while (condition);
Example:
#include <iostream>
using namespace std;
int main() {
int i = 0;
do {
cout << "Iteration: " << i << endl;
i++;
} while (i < 5);
return 0;
}
Execute Code
Block
Check
Repeat or Exit
Condition
Condition True?
For Loop
Use when the number of
iterations is known
beforehand.
Which loop to While Loop
use in C++?
Use when the number of
iterations is not known and
depends on a condition.
Do-While Loop
Use when the code block
needs to be executed at least
once.