C++ For Loop

In C++, for loops, foreach (range-based for) loops, and nested loops are essential constructs for controlling the flow of your program and iterating over data structures or performing repetitive tasks.

For Loop

A for loop in C++ is used when you know in advance how many times you want to repeat a set of statements. It consists of three parts: initialization, condition, and update.

Syntax
for (initialization; condition; update) { // Code to be executed repeatedly }
Example
#include <iostream> int main() { for (int i = 0; i < 5; i++) { std::cout << "Iteration " << i << std::endl; } return 0; }

In this example, the for loop initializes i to 0, checks if i is less than 5, and increments i by 1 in each iteration, executing the code inside the loop block.

Foreach (Range-Based For) Loop

The range-based for loop is introduced in C++11 and is used for iterating over elements in a range, such as arrays, vectors, or other containers. It simplifies the syntax for iteration.

Syntax
for (type var : range) { // Code to be executed for each element in the range }
Example
#include <iostream> #include <vector> int main() { std::vector<int> numbers = {1, 2, 3, 4, 5}; for (int num : numbers) { std::cout << num << " "; } return 0; }

This loop iterates over the elements of the numbers vector, assigning each element to the num variable, and prints the numbers.

Nested Loop

Nested loops are loops within loops. They are used when you need to perform repetitive tasks with multiple levels of iteration. Common use cases include processing 2D arrays or generating permutations.

Example
#include <iostream> int main() { for (int i = 0; i < 3; i++) { for (int j = 0; j < 2; j++) { std::cout << "i: " << i << ", j: " << j << std::endl; } } return 0; }

In this example, there are two nested for loops. The outer loop iterates from 0 to 2, and for each iteration of the outer loop, the inner loop iterates from 0 to 1. This results in a total of 6 iterations.

Nested foreach (range-based for) loops follow a similar structure, with one loop inside another, but they are used for iterating through elements in nested data structures like arrays of arrays or vectors of vectors.

Infinite for loop

An infinite for loop is a for loop that never terminates. Infinite for loops can be used to create programs that run continuously, such as a server or a game.

Example

The following example shows how to create an infinite for loop:

int main() { for (;;) { // Code to be executed } return 0; }

This loop will continue to iterate forever, or until the program is manually terminated.

Conclusion

A for loop in C++ is a control structure that iterates a block of code a specific number of times. It consists of an initialization, condition, and update statement, making it suitable for situations where the number of iterations is known in advance and requires precise control.