The for loop in C++ is a control flow statement that allows repetitive execution of a block of code for a fixed number of times or based on specific conditions. The for loop is commonly used when the number of iterations is known in advance.
Syntax of the for Loop
for (initialization; condition; update) { // Code to be executed in each iteration }
- Initialization: Initializes the loop counter, executed only once at the start of the loop.
- Condition: Checked before each iteration. If true, the loop continues; if false, the loop terminates.
- Update: Updates the loop counter after each iteration.
1. Basic for Loop Example
A basic for loop iterates a fixed number of times, printing numbers from 1 to 5.
#include <iostream> using namespace std; int main() { for (int i = 1; i <= 5; i++) { cout << "i = " << i << endl; } return 0; }
Explanation:
- int i = 1 initializes the loop variable i to 1.
- i <= 5 checks the condition; the loop runs as long as i is less than or equal to 5.
- i++ increments i by 1 after each iteration.
Output:
i = 1 i = 2 i = 3 i = 4 i = 5
2. for Loop with Multiple Variables
You can initialize and update multiple variables within a for loop.
#include <iostream> using namespace std; int main() { for (int i = 1, j = 10; i <= 5 && j >= 6; i++, j--) { cout << "i = " << i << ", j = " << j << endl; } return 0; }
Explanation:
- i is incremented and j is decremented in each iteration.
- The loop runs as long as both i <= 5 and j >= 6 conditions are true.
Output:
i = 1, j = 10 i = 2, j = 9 i = 3, j = 8 i = 4, j = 7 i = 5, j = 6
3. Calculating the Sum of the First n Numbers
Using a for loop to calculate the sum of the first n positive integers.
#include <iostream> using namespace std; int main() { int n, sum = 0; cout << "Enter a positive integer: "; cin >> n; for (int i = 1; i <= n; i++) { sum += i; // Adds i to sum in each iteration } cout << "Sum of first " << n << " numbers: " << sum << endl; return 0; }
Explanation:
- The for loop adds each number from 1 to n to sum.
- sum contains the total after the loop completes.
Sample Output:
Enter a positive integer: 5 Sum of first 5 numbers: 15
4. for Loop with Array Elements
The for loop is commonly used to iterate over arrays, accessing each element by index.
#include <iostream> using namespace std; int main() { int arr[] = {10, 20, 30, 40, 50}; int n = sizeof(arr) / sizeof(arr[0]); // Calculates number of elements for (int i = 0; i < n; i++) { cout << "arr[" << i << "] = " << arr[i] << endl; } return 0; }
Explanation:
- sizeof(arr) / sizeof(arr[0]) calculates the number of elements in the array.
- i goes from 0 to n-1, accessing each element by index.
Output:
arr[0] = 10 arr[1] = 20 arr[2] = 30 arr[3] = 40 arr[4] = 50
5. for Loop in Reverse
You can use a for loop to iterate in reverse by initializing the counter to the last element and decrementing it.
#include <iostream> using namespace std; int main() { for (int i = 5; i >= 1; i--) { cout << "i = " << i << endl; } return 0; }
Explanation:
- The loop starts from 5 and decrements i until i reaches 1.
Output:
i = 5 i = 4 i = 3 i = 2 i = 1
6. Infinite for Loop
An infinite for loop can be created by omitting the condition or by using true as the condition.
#include <iostream> using namespace std; int main() { for (;;) { // Infinite loop cout << "This loop runs forever!" << endl; break; // Comment this line to make the loop truly infinite } return 0; }
Explanation:
- for(;;) creates an infinite loop because no condition is specified.
- break is used to exit the loop, preventing an actual infinite loop.
Output:
This loop runs forever!
7. Using for Loop with break and continue
- break: Exits the loop immediately.
- continue: Skips the current iteration and moves to the next.
#include <iostream> using namespace std; int main() { for (int i = 1; i <= 10; i++) { if (i == 5) { continue; // Skip when i == 5 } if (i == 8) { break; // Exit the loop when i == 8 } cout << "i = " << i << endl; } return 0; }
Explanation:
- continue skips printing when i is 5.
- break exits the loop when i is 8.
Output:
i = 1 i = 2 i = 3 i = 4 i = 6 i = 7
8. Nested for Loop
A for loop inside another for loop is known as a nested for loop, useful for working with 2D arrays or patterns.
#include <iostream> using namespace std; int main() { for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { cout << i << "," << j << " "; } cout << endl; } return 0; }
Explanation:
- The outer loop controls rows, and the inner loop controls columns.
Output:
1,1 1,2 1,3 2,1 2,2 2,3 3,1 3,2 3,3
9. Using for Loop to Print Patterns
The for loop is often used to print patterns, such as triangles or squares.
#include <iostream> using namespace std; int main() { int rows = 5; for (int i = 1; i <= rows; i++) { for (int j = 1; j <= i; j++) { cout << "* "; } cout << endl; } return 0; }
Explanation:
- This nested for loop prints a right-angled triangle pattern.
- The outer loop controls the number of rows, and the inner loop prints stars based on the current row number.
Output:
* * * * * * * * * * * * * * *
10. Summary
Use Case | Code Example | Description |
---|---|---|
Basic for loop | for (int i = 0; i < n; i++) | Iterates a fixed number of times |
Multiple variables | for (int i=0, j=n; i<j; i++, j–) | Initializes and updates multiple variables |
Sum of numbers | for (int i=1; i<=n; i++) sum += i | Calculates sum of first n numbers |
Array iteration | for (int i=0; i<n; i++) cout << arr[i] | Accesses each array element |
Reverse iteration | for (int i=n; i>=1; i–) | Loops in reverse order |
Infinite loop | for (;;) | Creates an infinite loop |
break and continue | for (…) { if (cond) break; } | Controls loop flow with break and continue |
Nested loop | for (…) { for (…) { } } | Loop within a loop |
Pattern printing | for (…) { for (…) cout << “*”; } | Prints patterns such as triangles or squares |
Complete Example: Using for Loop for Multiple Tasks
This example combines several use cases of the for loop, including calculating a sum, iterating an array, and printing a pattern.
#include <iostream> using namespace std; int main() { // 1. Calculate the sum of the first 5 numbers int sum = 0; for (int i = 1; i <= 5; i++) { sum += i; } cout << "Sum of first 5 numbers: " << sum << endl; // 2. Iterating an array int arr[] = {10, 20, 30, 40, 50}; int n = sizeof(arr) / sizeof(arr[0]); cout << "Array elements: "; for (int i = 0; i < n; i++) { cout << arr[i] << " "; } cout << endl; // 3. Printing a triangle pattern cout << "Triangle pattern:" << endl; for (int i = 1; i <= 5; i++) { for (int j = 1; j <= i; j++) { cout << "* "; } cout << endl; } return 0; }
Sample Output:
Sum of first 5 numbers: 15 Array elements: 10 20 30 40 50 Triangle pattern: * * * * * * * * * * * * * * *
The for loop in C++ is powerful and versatile, allowing for a wide range of use cases, from basic iterations to complex patterns and calculations.