The Wayback Machine - https://web.archive.org/web/20240717024727/https://www.geeksforgeeks.org/cpp-for-loop/
Open In App

for Loop in C++

Last Updated : 21 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, for loop is an entry-controlled loop that is used to execute a block of code repeatedly for the specified range of values. Basically, for loop allows you to repeat a set of instructions for a specific number of iterations.

for loop is generally preferred over while and do-while loops in case the number of iterations is known beforehand.

Syntax of for Loop

The syntax of for loop in C++ is shown below:

for ( initialization; test condition; updation)
{ 
     // body of for loop
}
syntax breakdown of for loop in cpp

C++ for Loop Syntax Breakdown

The various parts of the for loop are:

1. Initialization Expression in for Loop

We have to initialize the loop variable to some value in this expression.

2. Test Condition in for Loop

In this expression, we have to test the condition. If the condition evaluates to true then we will execute the body of the loop and go to the update expression. Otherwise, we will exit from the for loop.

3. Update Expression in for Loop

After executing the loop body, this expression increments/decrements the loop variable by some value.

Flowchart of for Loop in C++

flowchart of for loop in C++

Flowchart of for Loop in C++

Execution Flow of a for Loop

  1. Control falls into the for loop. Initialization is done.
  2. The flow jumps to Condition.
  3. Condition is tested.
    • If the Condition yields true, the flow goes into the Body.
    • If the Condition yields false, the flow goes outside the loop.
  4. The statements inside the body of the loop get executed.
  5. The flow goes to the update.
  6. Updation takes place and the flow goes to Step 3 again.
  7. The for loop has ended and the flow has gone outside.

Examples of for Loop in C++

Example 1

The below example demonstrates the use of a for loop in a C++ program.

C++




// C++ program to illustrate for loop to print numbers from
// 1 to n
  
#include <iostream>
using namespace std;
  
int main()
{
    // initializing n (value upto which you want to print
    // numbers
    int n = 5;
    int i; // initialization of loop variable
    for (i = 1; i <= n; i++) {
        cout << i << " ";
    }
  
    return 0;
}


Output

1 2 3 4 5 

Explanation

The above program uses a for loop to print numbers from 1 to n (here n=5). The loop variable i iterates from 1 to n and in each iteration condition is checked (is i<=n i.e i<=5 ), if true then it prints the value of i followed by a space and increment i. When the condition is false loop terminates.

Example 2

Example to demonstrate the use of a for loop in a C++ program for printing numbers from n to 1 (i.e. reverse).

C++




// C++ program to illustrate for loop to print numbers from
// n to 1 (reverse counting).
  
#include <iostream>
using namespace std;
  
int main()
{
    // initializing n (value upto which you want to print
    // numbers
    int n = 5;
    int i; // initialization of loop variable
    for (i = n; i >= 1; i--) {
        cout << i << " ";
    }
  
    return 0;
}


Output

5 4 3 2 1 

Explanation
The above program uses a for loop to print numbers from n to 1 (here n=5) the loop variable i iterates from n to 1 and in each iteration condition is checked (is i>=1) if true then it prints the value of i followed by a space and decrement i. When the condition is false loop terminates.

So we can conclude that no matter what the updation is, as long as the condition is satisfied, for loop will keep executing.

Note: Scope of the loop variables that are declared in the initialization section is limited to the for loop block.

Example 3

The program demonstrates the use of a loop with different kinds of updation.

C++




// C++ program to illustrate the use of differnt loop
// updation
#include <iostream>
#include <string>
using namespace std;
  
// driver code
int main()
{
  
    // for loop with different kind of initialization
    for (int i = 32; i > 0; i = i / 2) {
        cout << "Geeks" << endl;
    }
  
    return 0;
}


Output

Geeks
Geeks
Geeks
Geeks
Geeks
Geeks

C++ Nested for Loop

A nested for loop is basically putting one loop inside another loop. Every time the outer loop runs, the inner loop runs all the way through. It’s a way to repeat tasks within tasks in your program.

Example of Nested for Loop

The below example demonstrates the use of Nested for loop in a C++ program.

C++




// C++ program to demonstrate the use of Nested for loop.
  
#include <iostream>
using namespace std;
  
int main()
{
    // Outer loop
    for (int i = 0; i < 4; i++) {
  
        // Inner loop
        for (int j = 0; j < 4; j++) {
  
            // Printing the value of i and j
            cout << "*"
                 << " ";
        }
        cout << endl;
    }
}


Output

* * * * 
* * * * 
* * * * 
* * * * 

Explanation

The above program uses nested for loops to print a 4×4 matrix of asterisks (*). Here, the outer loop (i) iterates over rows and the inner loop (j) iterates over columns. In each iteration, inner loop prints an asterisk and a space also new line is added after each row is printed.

Multiple Variables in for Loop

In the for loop we can initialize, test, and update multiple variables in the for loop.

Example of Using Multiple Variables in for Loop

The below example demonstrates the use of multiple variables for loop in a C++ program.

C++




// C++ program to demonstrate the use of multiple variables
// in for loops
  
#include <iostream>
using namespace std;
  
int main()
{
    // initializing loop variable
    int m, n;
  
    // loop having multiple variable and updations
    for (m = 1, n = 1; m <= 5; m += 1, n += 2) {
        cout << "iteration " << m << endl;
        cout << "m is: " << m << endl;
        cout << "j is: " << n << endl;
    }
  
    return 0;
}


Output

iteration 1
m is: 1
j is: 1
iteration 2
m is: 2
j is: 3
iteration 3
m is: 3
j is: 5
iteration 4
m is: 4
j is: 7
iteration 5
m is: 5
j is: 9

Explanation
The above program uses for loop with multiple variables (here m and n). It increments and updates both variables in each iteration and prints their respective values.

C++ Infinite for Loop

When no parameters are given to the for loop, it repeats endlessly due to the lack of input parameters, making it a kind of infinite loop.

Example of Infinite for Loop

The below example demonstrates the use of multiple variables for loop in a C++ program.

C++




// C++ Program to demonstrate infinite loop
  
#include <iostream>
using namespace std;
  
int main()
{
    // skip Initialization, test and update conditions
    for (;;) {
        cout << "gfg" << endl;
    }
    // Return statement to show program compiles
    // successfully safely
    return 0;
}


Output

gfg
gfg
.
.
.
infinite times

Range-Based for Loop in C++

C++ range-based for loops execute for loops over a range of values, such as all the elements in a container, in a more readable way than the traditional for loops.

Syntax:

for ( range_declaration : range_expression )     {        
// loop_statements here
  }
  • range_declaration: to declare a variable that will take the value of each element in the given range expression.
  • range_expression: represents a range over which loop iterates.

Example of Range-Based for Loop

The below example demonstrates the use of a Range-Based loop in a C++ program.

C++




// C++ Program to demonstrate the use of range based for
// loop in C++
#include <iostream>
#include <vector>
using namespace std;
  
int main()
{
    int arr[] = { 10, 20, 30, 40, 50 };
  
    cout << "Printing array elements: " << endl;
    // range based for loop
    for (int& val : arr) {
        cout << val << " ";
    }
    cout << endl;
  
    cout << "Printing vector elements: " << endl;
    vector<int> v = { 10, 20, 30, 40, 50 };
  
    // range-based for loop for vector
    for (auto& it : v) {
        cout << it << " ";
    }
    cout << endl;
  
    return 0;
}


Output

Printing array elements: 
10 20 30 40 50 
Printing vector elements: 
10 20 30 40 50 

Explanation:
The above program shows the use of a range-based for loop. Iterate through each element in an array (arr here) and a vector (v here) and print the elements of both.

for_each Loop in C++

C++ for_each loop accepts a function that executes over each of the container elements.

This loop is defined in the header file <algorithm> and hence has to be included for the successful operation of this loop.

Syntax of for_each Loop

for_each ( InputIterator start_iter, InputIterator last_iter, Function fnc);

Parameters

  • start_iter: Iterator to the beginning position from where function operations have to be executed.
  • last_iter: Iterator to the ending position till where function has to be executed.
  • fnc: The 3rd argument is a function or a function object which would be executed for each element.

Example of for_each Loop

The below example demonstrates the use of for_each loop in a C++ program.

C++




// C++ Program to show use of for_each loop
  
#include <bits/stdc++.h>
using namespace std;
  
// function to print values passed as parameter in loop
void printValues(int i) { cout << i << " " << endl; }
  
int main()
{
    // initializing vector
    vector<int> v = { 1, 2, 3, 4, 5 };
  
    // iterating using for_each loop
    for_each(v.begin(), v.end(), printValues);
  
    return 0;
}


Output

1 
2 
3 
4 
5 

Explanation:
The above program uses for_each loop to iterate through each element of the vector (v here), it calls the printValues function to print each element. Output is displayed in the next line for each iteration.

Related Articles



Previous Article
Next Article

Similar Reads

Difference between Open-Loop Control System and Closed-Loop Control System
Control System is a system in which the behavior of the system is determined by a differential equation. It manages the devices and the systems using control loops. There are Open-Loop Control System and Closed-Loop Control System. Open-Loop Control System is used in applications in which no feedback and error handling are required. It is simple an
3 min read
Time Complexity of a Loop when Loop variable “Expands or Shrinks” exponentially
For such cases, time complexity of the loop is O(log(log(n))).The following cases analyse different aspects of the problem. Case 1 : for (int i = 2; i &lt;=n; i = pow(i, k)) { // some O(1) expressions or statements } In this case, i takes values 2, 2k, (2k)k = 2k2, (2k2)k = 2k3, ..., 2klogk(log(n)). The last term must be less than or equal to n, an
1 min read
Print a character n times without using loop, recursion or goto in C++
Given a character c and a number n, print the character c, n times. We are not allowed to use loop, recursion, and goto. Examples : Input : n = 10, c = 'a'Output : aaaaaaaaaa Input : n = 6, character = '@'Output : @@@@@@ In C++, there is a way to initialize a string with a value. It can be used to print a character as many times as we want. While d
2 min read
Difference between while and do-while loop in C, C++, Java
while loop: A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement. Syntax : while (boolean condition) { loop statements... } Flowchart: Example: C/C++ Code #include &lt;stdio.h&gt; int main() { int i = 5; while (i &lt; 10)
2 min read
C++ While Loop
While Loop in C++ is used in situations where we do not know the exact number of iterations of the loop beforehand. The loop execution is terminated on the basis of the test condition. Loops in C++ come into use when we need to repeatedly execute a block of statements. During the study of the 'for' loop in C++, we have seen that the number of itera
3 min read
Java do-while loop with Examples
Loops in Java come into use when we need to repeatedly execute a block of statements. Java do-while loop is an Exit control loop. Therefore, unlike for or while loop, a do-while check for the condition after executing the statements of the loop body. Syntax: do { // Loop Body Update_expression } // Condition check while (test_expression); Note: The
5 min read
C++ Do/While Loop
Loops come into use when we need to repeatedly execute a block of statements. Like while the do-while loop execution is also terminated on the basis of a test condition. The main difference between a do-while loop and a while loop is in the do-while loop the condition is tested at the end of the loop body, i.e do-while loop is exit controlled where
3 min read
Different types of range-based for loop iterators in C++
Range-Based 'for' loops have been included in the language since C++11. It automatically iterates (loops) over the iterable (container). This is very efficient when used with the standard library container (as will be used in this article) as there will be no wrong access to memory outside the scope of the iterable. The loop will automatically star
5 min read
Generic For Loop in Java
When we know that we have to iterate over a whole set or list, then we can use Generic For Loop. Java's Generic has a new loop called for-each loop. It is also called enhanced for loop. This for-each loop makes it easier to iterate over array or generic Collection classes. In normal for loop, we write three statements : for( statement1; statement 2
4 min read
While loop with Compile time constants
While loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement. It is mostly used in situations where the exact number of iterations beforehand. Below is the image to illustrate the while loop: Syntax: while(test_expression){ // state
6 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg