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.
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
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
This loop iterates over the elements of the numbers vector, assigning each element to the num variable, and prints the numbers.
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
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:
This loop will continue to iterate forever, or until the program is manually terminated.
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.