n C++, loops are used to execute a block of code repeatedly, based on a condition. There are three main types of loops:
1. for loop
The for loop is used when the number of iterations is known before entering the loop. It’s structured in a way that allows initialization, condition checking, and updating of the loop variable all in one line.
Syntax:
for (initialization; condition; update) {
// Code to be executed
}
- Initialization: Set the initial value of the loop counter.
- Condition: The loop continues as long as the condition is true.
- Update: Updates the loop counter (increment or decrement).
Example:
for (int i = 0; i < 5; i++) {
cout << i << endl;
}
This loop prints the values from 0 to 4. Here, i is initialized to 0, the loop runs while i is less than 5, and i is incremented after each iteration.
Use case:
Use the for loop when the number of iterations is known in advance, such as when iterating through an array or a known range of numbers.
2. while loop
The while loop is used when the number of iterations is not known beforehand. The loop will continue running as long as the condition remains true. It checks the condition before executing the loop body.
Syntax:
while (condition) {
// Code to be executed
}
- Condition: The loop runs while this condition is true.
Example:
int i = 0;
while (i < 5) {
cout << i << endl;
i++;
}
This loop also prints the values from 0 to 4, but here the number of iterations is determined by the value of i and how it changes inside the loop.
Use case:
Use the while loop when the number of iterations depends on a condition that might change during execution, such as reading input until a user enters a specific value.
3. do-while loop
The do-while loop is similar to the while loop, but with one key difference: it checks the condition after executing the loop body, ensuring the loop runs at least once, even if the condition is false at the start.
Syntax:
do {
// Code to be executed
} while (condition);
- Condition: The loop continues if this condition is true, but it’s evaluated after the first iteration.
Example:
int i = 0;
do {
cout << i << endl;
i++;
} while (i < 5);
This loop prints values from 0 to 4, but even if i were initially greater than 5, the loop would still execute at least once before checking the condition.
Use case:
Use the do-while loop when you want the loop to always execute at least once, such as when prompting a user for input where you want the prompt to appear before checking the input.


.jpg)

Quite good 👍
ReplyDeleteFantastic
ReplyDeleteperfect
ReplyDeleteWonderful , keep going
ReplyDeleteRight on point keep it up
ReplyDeletewow!!
ReplyDeleteCool
ReplyDeleteGreat work
ReplyDelete