for Loop in C++ - GeeksforGeeks (2024)

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}

for Loop in C++ - GeeksforGeeks (1)

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++

for Loop in C++ - GeeksforGeeks (2)

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;

}

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

GeeksGeeksGeeksGeeksGeeksGeeks

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 1m is: 1j is: 1iteration 2m is: 2j is: 3iteration 3m is: 3j is: 5iteration 4m is: 4j is: 7iteration 5m is: 5j 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

gfggfg...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

  • C++ while loop with Examples
  • C++ do while loop with Examples
  • Difference between while and do-while loop in C++
  • Difference between for and while loop in C++


C

Chinmoy Lenka

Improve

Previous Article

C++ Loops

Next Article

C++ While Loop

Please Login to comment...

for Loop in C++ - GeeksforGeeks (2024)

References

Top Articles
Latest Posts
Article information

Author: Rev. Leonie Wyman

Last Updated:

Views: 5907

Rating: 4.9 / 5 (59 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Rev. Leonie Wyman

Birthday: 1993-07-01

Address: Suite 763 6272 Lang Bypass, New Xochitlport, VT 72704-3308

Phone: +22014484519944

Job: Banking Officer

Hobby: Sailing, Gaming, Basketball, Calligraphy, Mycology, Astronomy, Juggling

Introduction: My name is Rev. Leonie Wyman, I am a colorful, tasty, splendid, fair, witty, gorgeous, splendid person who loves writing and wants to share my knowledge and understanding with you.