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)

FAQs

What is a for loop in C++? ›

A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.

What is the syntax of for loop? ›

The Difference Between For Loop - While Loop - Do-While Loop
DifferenceFor LoopWhile Loop
Syntaxfor(init; condition; icr/dcr){ //statements to be repeated }while(condition){ //statements to be repeated }
Examplefor(int x=0; x<=5; x++){ System.out.println(x); }int x=0; while(x<=5){ System.out.println(x); x++; }
2 more rows
Jun 10, 2024

What is I ++ and ++ I in for loop? ›

++i and i++ both increment the value of i by 1 but in a different way. If ++ precedes the variable, it is called pre-increment operator and it comes after a variable, it is called post-increment operator.

What is the difference between for loop and while loop in C++? ›

The for loop provides its users with a concise way in which they can write the loop structure. It provides a very easy to debug and short looping structure. The while loop is a type of continuous flow statement that basically allows the repeated execution of a code on the basis of any given Boolean condition.

What is the purpose of a for loop? ›

A "For" Loop is used to repeat a specific block of code a known number of times. For example, if we want to check the grade of every student in the class, we loop from 1 to that number. When the number of times is not known before hand, we use a "While" loop.

What is the general format of the for loop? ›

The for-loop, written as [initial] [increment] [limit] { ... } for initialises an internal variable, executes the body as long as the internal variable is not more than limit (or not less, if increment is negative) and, at the end of each iteration, increments the internal variable.

How do you start writing a for loop in C? ›

C for loop Examples
  1. #include<stdio.h>
  2. int main(){
  3. int i=0;
  4. for(i=1;i<=10;i++){
  5. printf("%d \n",i);
  6. }
  7. return 0;
  8. }

What are the 3 parts of a for loop? ›

There are three parts in a for loop header: the initialization, the test condition (a Boolean expression), and an increment or decrement statement to change the loop control variable. In a for loop, the initialization statement is only executed once before the evaluation of the test Boolean expression.

What does == mean in C++? ›

The assignment operator (operator = , with one equal sign) is not the same as the equality comparison operator (operator == , with two equal signs); the first one ( = ) assigns the value on the right-hand to the variable on its left, while the other ( == ) compares whether the values on both sides of the operator are ...

What's the difference between I ++ and ++ I in C++? ›

i++: Here, the value of i is returned first, then it is incremented. In a common example, if you set i = 1, and x = i++, you should find that x = 1. This is called post increment. ++i: In this case, i is first incremented and then returned.

How many sections are there in for loop? ›

A for loop has two parts: a header specifying the iteration, and a body which is executed once per iteration. The header often declares an explicit loop counter or loop variable, which allows the body to know which iteration is being executed.

What are the advantages of a for loop over a while loop? ›

The main advantage of a for loop over a while loop is readability. A For loop is a lot cleaner and a lot nicer to look at. It's also much easier to get stuck in an infinite loop with a while loop.

Is while faster than for C++? ›

None of them is faster. For-loops are used when you already know how often you want to loop trough. While-loops are used when you are not sure how often you want to loop or if you even have to start the loop. Do-loops are used like While-loops, except that do-loops will always run at least once.

What is a for loop used for in C? ›

The for loop in C language is used to iterate the statements or a part of the program several times. It is frequently used to traverse the data structures like the array and linked list.

What is the use of for each loop in C++? ›

The working of foreach loops is to do something for every element rather than doing something n times. There is no foreach loop in C, but both C++ and Java support the foreach type of loop. In C++, it was introduced in C++ 11 and Java in JDK 1.5. 0 The keyword used for foreach loop is “for” in both C++ and Java.

What is loop with example? ›

Definition of Loop in Programming

Definite loops: These have a predetermined number of iterations. An example of a definite loop is the 'for' loop, where you define the start and end of the loop beforehand.

Top Articles
Latest Posts
Article information

Author: Sen. Emmett Berge

Last Updated:

Views: 5530

Rating: 5 / 5 (80 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Sen. Emmett Berge

Birthday: 1993-06-17

Address: 787 Elvis Divide, Port Brice, OH 24507-6802

Phone: +9779049645255

Job: Senior Healthcare Specialist

Hobby: Cycling, Model building, Kitesurfing, Origami, Lapidary, Dance, Basketball

Introduction: My name is Sen. Emmett Berge, I am a funny, vast, charming, courageous, enthusiastic, jolly, famous person who loves writing and wants to share my knowledge and understanding with you.