For Loop
The for
Loop in C++:
The for
loop in C++ is a versatile loop structure that allows you to execute a block of code repeatedly for a specific number of iterations. It consists of three main parts: initialization, condition, and iteration expression. The basic syntax of a for
loop is as follows:
for (initialization; condition; iteration) {
// Code to be executed in each iteration
}
Here's an example of a simple for
loop that prints the numbers from 1 to 5:
#include <iostream>
int main() {
for (int i = 1; i <= 5; ++i) {
std::cout << i << " ";
}
return 0;
}
In this example:
int i = 1
is the initialization part, where you declare and initialize a loop control variablei
.i <= 5
is the condition part, which is checked before each iteration. The loop continues as long as this condition is true.++i
is the iteration part, which is executed after each iteration. It increments the loop control variable.
The output of this program will be:
1 2 3 4 5
You can customize the for
loop based on your specific requirements. For example, you can change the initialization, condition, or iteration expressions to create loops with different behaviors.
#include <iostream>
int main() {
// Loop with a different initialization and iteration
for (int i = 10; i >= 1; --i) {
std::cout << i << " ";
}
std::cout << std::endl;
// Loop with a different initialization, condition, and iteration
for (int i = 0; i < 20; i += 2) {
std::cout << i << " ";
}
return 0;
}
In these examples, the first loop counts down from 10 to 1, and the second loop counts even numbers from 0 to 18.
Remember to use break
and continue
statements when necessary to control the flow of the loop. The break
statement can be used to exit the loop prematurely, and the continue
statement can be used to skip the rest of the loop body and move to the next iteration.