C++ For loop
The for loop is a control flow statement in C++ that enables you to repeatedly run a block of code for a predetermined number of times.
Basic syntax of for loop:
for (initialization; condition; update) {
// Code block to be executed repeatedly
}
The initial value of the loop control variable is set by the initialization expression, which is only executed once at the start of the loop. Each time the loop iterates, the condition expression is tested to see if it is true. If it is, the loop then continues to run. The loop ends if the condition is false. At the conclusion of each iteration, the update expression is used to change the value of the loop control variable.

Example of for loop:
#include <iostream>
int main() {
for (int i = 1; i <= 5; i++) {
std::cout << i << "\n";
}
return 0;
}
Output:
1
2
3
4
5
In this illustration, the loop’s control variable “i” is initially set to 1, and it runs until “i” drops below or equals 5. Simply printing the value of “i” to the console, followed by a newline character, is all that the code block inside the loop does. The value of “i” is raised by 1 at the conclusion of each iteration.
Here, we first take input from the user for the number whose factorial needs to be calculated. Then, we use a for loop to calculate the factorial of the number. The loop starts from 1 and iterates until the number itself, multiplying the value of fact by the loop variable i in each iteration. Finally, we print out the result.
Advantages of for loop:
The for loop can be used to run a piece of code a certain number of times.
For iterating over a range of values, it offers a straightforward and condensed syntax.
It enables more precise control over the loop’s variables and its iteration count.
It is quicker to iterate over a range of numbers than the while loop and do-while loop.
Disadvantages of for loop:
- When iterating through intricate data structures like linked lists or trees, it might be challenging.
- For some sorts of loops, including those that depend on user input to decide when to stop iterating, it could be less simple to use.
- When the number of iterations is uncertain or unexpected, it is not appropriate.