C++ For Loop - C++ Programming Tutorial

C++ For Loop

BLUF: Mastering C++ For Loop is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: C++ For Loop

C++ is renowned for its efficiency. Learn how C++ For Loop enables low-level control and high-performance computing in the tutorial below.

In C++, the for loop is a type of loop that is controlled by an entry condition and is primarily used to repeat a section of the program multiple times. When the number of repetitions is predetermined, it is advisable to opt for the for loop instead of while or do-while loops.

Syntax

The C++ for loop functions similarly to for loops in various other programming languages like C and C#. It allows for variable initialization, condition checking, and incrementing/decrementing values.

Example

for(initialization; condition; update){    

//code to be executed    

}
  • Initialization: It initializes the variables and is executed only once.
  • Condition Statement: The condition statement checks the given condition. If the condition is true, it executes the of for loop. If the condition is false, it terminates the for loop.
  • Update Expression: After execution of the loop body, this expression increments or decrements the loop variable by 1.
  • Flowchart of for Loop

As illustrated in the flow diagram, adhere to the listed instructions to incorporate the for loop in C++:

Commence by navigating to the for loop and setting up the variables along with their respective initial values.

Step 2: Subsequently, the program flow transfers to the conditional statement.

Step 3: In this step, the program evaluates the condition:

If the condition evaluates to true, the code within the loop is executed.

If the condition evaluates to false, the loop is exited, and the program moves on to the next iteration.

Afterwards, the program proceeds to the update expression, where it either increments or decrements the value by 1. Subsequently, it loops back to step 3 to evaluate the condition once more.

At the final step, the loop is exited, and the output is displayed.

Simple C++ for Loop Example

Let's consider a basic illustration of displaying the numbers 1 through 10 utilizing the C++ for loop.

Example

Example

#include <iostream>  

using namespace std;  //using standard namespace

int main() //main function

{  

         for(int i=1;i<=10;i++) //code of C++ for loop

{      

            cout<<i <<"\n";      

          }       

    }

Output:

Output

1

2

3

4

5

6

7

8

9

10

Factorial Program using C++ for Loop

Let's consider another illustration to calculate the factorial of a specified number by employing a for loop in C++.

Example

Example

#include <iostream>

using namespace std; //using the standard namespace

// main code

int main() {

    int n;

    int fact = 1;

    cout << "Enter a positive number: ";

    cin >> n;

    // for loop calculating factorial

    for (int i = 1; i <= n; i++) {

        fact = fact * i;

    }

    cout << "The factorial of " << n << " is: " << fact; //print the output 

    return 0; 

}

Output:

Output

Enter a positive number: 6

The factorial of 6 is: 720

Multiplication table program using for loop in C++

Let's consider an instance involving displaying a multiplication chart using a for loop in C++.

Example

Example

#include <iostream>

using namespace std; //using standard namespace

 

// main function

int main()

{

    

    int n;

    cout<<"Enter a Number: ";

    cin >> n;

    

    for (int i = 1; i <= 10; ++i) //for loop

        cout << n << " * " << i << " = " << n * i << endl;

    return 0;

}

Output:

Output

Enter a Number: 4

4 * 1 = 4

4 * 2 = 8

4 * 3 = 12

4 * 4 = 16

4 * 5 = 20

4 * 6 = 24

4 * 7 = 28

4 * 8 = 32

4 * 9 = 36

4 * 10 = 40

C++ Nested for Loop

In C++, when a for loop is contained within another for loop, it is referred to as a nested for loop. The inner loop runs in its entirety each time the outer loop runs.

It enables us to carry out intricate iterations by running a for loop within each iteration of the outer for loop. Nested for loops are advantageous when dealing with multi-dimensional arrays or intricate patterns.

Syntax:

It has the following syntax:

Example

for (initialization; condition; increment) {  

    for (initialization; condition; increment) {  

        // statement of  inner loop

    }  

       //statement of outer loop

}

Flowchart of Nested for loop:

C++ Nested for Loop Example:

Let's consider a basic illustration of a nested for loop in C++.

Example

Example

#include <iostream>  

using namespace std; //using standard namespace

   

int main () //main function

    {  

        for(int i=1;i<=3;i++) //outer for loop 

        {      

             for(int j=1;j<=3;j++) //inner for loop

             {      

            cout<<i<<" "<<j<<"\n"; //print the value of i and j   

          }     

        }  

}

Output:

Output

1 1

1 2

1 3

2 1

2 2

2 3

3 1

3 2

3 3

C++ Pyramid Program using Nested for Loop:

Let's consider an instance where we aim to display a pyramid structure by employing nested for loops in the C++ programming language.

Example

Example

#include <iostream>

using namespace std;

// main function

int main()

{

    int n;

    cout << "Enter the Number of rows: "; 

    cin >> n;

    // Outer loop to handle number of rows

    for (int i = 0; i < n; i++) {

        // Inner loop to handle number of columns

        for (int j = 0; j <= i; j++) {

            cout << "* "; // Printing stars

        }

        cout << endl; // moves to the new line after every row

    }

}

Output:

Output

Enter the Number of rows: 6

* 

* * 

* * * 

* * * * 

* * * * * 

* * * * * *

Explanation:

In this instance, we are utilizing two for loops. The initial loop manages the row count, while the subsequent loop manages the column count and displays asterisks.

C++ Inverted Pyramid Program using Nested for Loop:

Let's consider an instance to display an upside-down pyramid pattern by employing nested for loops in C++.

Example

Example

#include <iostream>

using namespace std;

// main function

int main()

{

    int n;

    cout << "Enter the Number of rows: "; 

    cin >> n;

    // Outer loop to handle number of rows

    for (int i = 0; i < n; i++) {

        // Inner loop to handle number of columns

        for (int j = n; j > i; j--) {

            cout << "* "; // Printing stars

        }

        cout << endl; // moves to the new line after every row

    }

}

Output:

Output

Enter the Number of rows: 5

* * * * * 

* * * * 

* * * 

* * 

*

Explanation:

In this instance, we are utilizing two for loops. In this case, the outer loop manages the row count, while the inner loop manages the star count within each row.

C++ foreach Loop

The range-based for loop, commonly referred to as the foreach loop, is primarily used for iterating through the elements of a container like a list, array, vector, etc. This loop simplifies the iteration process by eliminating the need for initialization, increment/decrement, and testing. In C++, the foreach loop is implemented using the 'for' keyword.

Syntax:

It has the following syntax:

Example

for (data_type  variable_name : container_name) {

     // code to be executed

}

In this particular format,

  • Variable_name: Refers to the identifier assigned to the elements contained within a specific data structure.
  • Container_name: Represents the name assigned to a data structure such as a list, array, vector, or similar container types.
  • C++ Foreach Loop Example:

Let's consider a scenario to demonstrate the foreach loop in C++.

Example

Example

#include <iostream>

#include <vector> //vector library

using namespace std; //using standard namespace

int main() //main function

{

   vector<int> numbers = {15, 20, 25, 30, 35};

   // Range-based for loop to modify each element

   for (int& num : numbers) {

      num += 5; // add 5 for each number

   }

   for (int num : numbers) {

      cout << num << " "; //prints the output

   }

   cout << endl;

   return 0;

}

Output:

Output

20 25 30 35 40

Explanation:

In this instance, we have selected a vector library to implement dynamic arrays. Subsequently, we define a vector containing integers. Following this, we incorporate two for loops within the code. The initial loop employs a reference to alter the elements within the vector, while the subsequent loop displays the adjusted values.

C++ Infinite for Loop

In C++, excluding the initialization, condition, and update expression will lead to an endless loop.

In simpler terms, employing a double semicolon within the for loop will result in it running endlessly.

Syntax:

It has the following syntax:

Example

for (; ; ){    

//code to be executed    

}

C++ Infinite For Loop Example:

Let's consider a scenario to demonstrate the infinite for loop in C++.

Example

Example

#include <iostream>  

using namespace std;  

 

int main () //main function

   {  

        for (; ;)  //infinite for loop

          {    

                  cout<<"Hello! Logic </> practice";    //prints the output

          }    

    }

Output:

Output

Hello! Logic </> practice 

Hello! Logic </> practice 

Hello! Logic </> practice

Hello! Logic </> practice

Here, it is necessary to use Ctrl+C to terminate the infinite program.

C++ for Loop MCQs

  1. In for loop, which of the following operators is utilized to separate expressions in C++?
  • Colon (:)
  • Semicolon (;)
  • Ampersand (&)
  • Comma (,)
  1. Which of the following options is the first expression of for loop in C++?
  • Condition
  • Increment/decrement
  • Initialization
  • None of the above
  1. What is the expected result of the code snippet provided below?
Example

int main() {

    for (int i = 1; i <= 5; i++) {

        cout << i << " ";

    }

    return 0;

}
  • 1 2 3 4 5
  • 1 2 3 4 5 6
  • 1 2 3 4
  • 0 1 2 3 4 5
  1. What type of loop is the for loop in C++ programming?
  • Exit-controlled loop
  • Recursive loop
  • Infinite loop
  • Entry-controlled loop
  1. Can we utilize the multiple initialization and update expression in a for loop in C++?
  • Only in C
  • Only in while loops

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience