C++ for loop
In this article, we will learn the usage of for
loop in C++ programming. Through various examples, we will gain a better understanding of how these loops work and how they can be utilized in our programs.
Loops are a fundamental component of computer programming, allowing us to repeat a specific block of code multiple times. In C++, there are three types of loops:
for
loop,while
loopdo...while
loop.
Each type of loop has its own unique features and use cases, and in this tutorial, we will focus on the for
loop.
The for
loop is a control structure in C++ that allows you to repeat a set of statements a specified number of times. The basic syntax of the for
loop is as follows:
1for (initialization; condition; increment/decrement) 2{ 3 // code to be executed 4}
Here, the initialization
section is executed only once, and it is used to initialize the loop control variable.
The condition
is evaluated on each iteration of the loop, and the loop continues to execute as long as the condition is true.
The increment/decrement
section is executed after each iteration of the loop, and it is used to change the value of the loop control variable.
Let's take a look at two examples of for
loops in C++ and their output:
Simple For Loop
1#include <iostream> 2using namespace std; 3 4int main() 5{ 6 for (int i = 1; i <= 5; i++) 7 { 8 cout << "Value of i: " << i << endl; 9 } 10 11 return 0; 12}
In the above example, the for
loop initializes the value of i
to 1 and continues to execute as long as i
is less than or equal to 5. The value of i
is incremented by 1 after each iteration of the loop. The output will be:
1Value of i: 1 2Value of i: 2 3Value of i: 3 4Value of i: 4 5Value of i: 5
Nested For Loop
1#include <iostream> 2using namespace std; 3 4int main() 5{ 6 for (int i = 1; i <= 3; i++) 7 { 8 for (int j = 1; j <= 2; j++) 9 { 10 cout << "Value of i: " << i << " and j: " << j << endl; 11 } 12 } 13 14 return 0; 15}
In the above example, the outer for
loop initializes the value of i
to 1 and continues to execute as long as i
is less than or equal to 3. The inner for
loop initializes the value of j
to 1 and continues to execute as long as j
is less than or equal to 2. The output will be:
1Value of i: 1 and j: 1 2Value of i: 1 and j: 2 3Value of i: 2 and j: 1 4Value of i: 2 and j: 2 5Value of i: 3 and j: 1 6Value of i: 3 and j: 2