Course Content
C++ Introduction
0/1
C++ Variables & Constants
0/1
C++Scope of Variable
0/1
C++ Keywords & Identifiers
0/1
C++ Data Types
0/1
C++ Basic I/O
0/1
C++ Type Conversion
0/1
C++ Operators
0/1
C++ Comments
0/1
C++ If-else
0/1
C++ Ternary Operator
0/1
C++ for Loop
0/1
C++ Ranged for Loop
0/1
C++ while/do-while Loop
0/1
C++ break Statement
0/1
C++ Continue Statement
0/1
C++ switch Statement
0/1
C++ goto Statement
0/1
C++ Functions
0/1
C++ User-defined Functions
0/1
C++ Default Arguments
0/1
C++ Storage Class
0/1
C++ Recursion
0/1
C++ Return by Reference
0/1
C++ Arrays
0/1
C++ Multi-dimentional Arrays
0/1
C++ Arrays & Function
0/1
C++ String
0/1
C++ Structure
0/1
C++ Structure & Functions
0/1
C++ Pointers to Structure
0/1
C++ Pointers
0/1
C++ Void Pointers
0/1
C++ Pointers & Arrays
0/1
C++ Pointers & Functions
0/1
C++ Dynamic Memory Allocation
0/1
C++ OOPs Concepts
0/1
C++ Objects and Class
0/1
C++ Constructors
0/1
C++ Destructors
0/1
C++ Constructor Overloading
0/1
C++ Objects & Function
0/1
C++ Enumeration
0/1
C++ Inheritance
0/1
C++ Inheritance Access Control
0/1
C++ Inheritance Types
0/1
C++ Polymorphism
0/1
C++ Function Overloading
0/1
C++ Function Overriding
0/1
C++ Operator Overloading
0/1
C++ Friend Function
0/1
C++ Virtual Function
0/1
C++ Abstract Class & Pure Virtual Function
0/1
C++ Encapsulation
0/1
C++ Abstraction
0/1
C++ Templates
0/1
C++ Exception Handling
0/1
C++ Multithreading
0/1
C++ Standard Library
0/1
C++ Programming Tutorials
About Lesson

C++ For Loop

In this tutorial, we will learn about the C++ loops, for loop, nested for loop rang,e-based, and infinite for loop and its working with the help of some examples.


C++ Loops

In computer programming, loops are used to repeat a block of code. Loops in Programming come into use when we need to repeatedly a block of statements.
For example, let’s say we want to show a message 100 times. Then instead of writing the print statement 100 times, we can use a loop.
That was just a simple example; we can achieve much more efficiency and sophistication in our programs by making effective use of loops.

In programming, a loop is a sequence of instructions that is repeated until a certain condition is reached.


Types of Loops

There are 3 types of loops in C++:
1) for loop
2) while loop
3) do...while loop

This tutorial focuses on C++ for loop. We will learn about the other type of loops in the upcoming tutorials.


C++ for loop

  • For loop is a Entry Controlled Loop or we can say repetition control structure.
  • It allows us to write a loop that is executed a specific number of times.
  • The loop enables us to perform ‘n’ number of steps together in one line.
  • For loop is used to execute a set of statement repeatedly until a particular condition is satisfied.

The syntax of for-loop is:

for (initialization; condition; update) {
    // body of-loop 
}

Here,

  • initialization – initializes variables and is executed only once
  • condition – if true, the body of for loop is executed
    if false, the for loop is terminated
  • update – updates the value of initialized variables and again checks the condition

To learn more about conditions, check out our tutorial on C++ Relational and Logical Operators.


Flowchart of for Loop in C++

C++ for loop flowchart
Flowchart of for loop in C++

Example 1: Print Numbers From 1 to 5

#include <iostream>     
using namespace std;
      
int main() {
        for (int i = 1; i <= 5; ++i) {
        cout << i << " ";
    }
    return 0;
}

Output

1 2 3 4 5

Here is how this program works

Iteration Variable i <= 5 Action
1st i = 1 true 1 is printed. i is increased to 2.
2nd i = 2 true 2 is printed. i is increased to 3.
3rd i = 3 true 3 is printed. i is increased to 4.
4th i = 4 true 4 is printed. i is increased to 5.
5th i = 5 true 5 is printed. i is increased to 6.
6th i = 6 false The loop is terminated

Example 2: Display a text 5 times

// C++ Program to display a "Hello World!" 5 times using For loop
      
#include <iostream>
      
using namespace std;
      
int main() {
    for (int i = 1; i <= 5; ++i) {
        cout <<  "Hello World! " << endl;
    }
    return 0;
}

Output

Hello World!
Hello World!
Hello World!
Hello World!
Hello World!

Here is how this program works

Iteration Variable i <= 5 Action
1st i = 1 true Hello World! is printed and i is increased to 2.
2nd i = 2 true Hello World! is printed and i is increased to 3.
3rd i = 3 true Hello World! is printed and i is increased to 4.
4th i = 4 true Hello World! is printed and i is increased to 5.
5th i = 5 true Hello World! is printed and i is increased to 6.
6th i = 6 false The loop is terminated

Example 3: Find the sum of first n Natural Numbers

// C++ program to find the sum of first n natural numbers using For Loop
// positive integers such as 1,2,3,...n are known as natural numbers
      
#include <iostream>

using namespace std;
      
int main() {
    int num, sum;
    sum = 0;
      
    cout << "Enter a positive integer: ";
    cin >> num;
      
    for (int count = 1; count <= num; ++count) {
        sum += count;
    }
      
    cout << "Sum = " << sum << endl;
      
    return 0;
}

Output

Enter a positive integer: 5
Sum = 15

In the above example, we have two variables num and sum. The sum variable is assigned with 0 and the num variable is assigned with the value provided by the user.

Note that we have used a for loop.

for(int count = 1; count <= num; ++count)

Here,

  • int count = 1: initializes the count variable
  • count <= num: runs the loop as long as count is less than or equal to num
  • ++count: increase the count variable by 1 in each iteration

When count becomes 6, the condition is false and sum will be equal to 0 + 1 + 2 + ... + 5.


Nested For Loop

  • A for loop within another for loop is called Nested For loop

The syntax of nested for loop is:

for (initialization; condition; update) {
        for (initialization; condition; update) {
                // body of inner for-loop 
        }
    // body of outer for-loop 
}

Example 4: Program to display a triangular pattern

// C++ program to display a triangular pattern 
// with 5 rows
                                            
#include <iostream>
using namespace std;
                                            
int main() {
                                            
   int rows = 5;
                                            
   for (int i = 1; i <= rows; ++i) {
      for (int j = 1; j <= i; ++j) {
         cout << "*  ";
      }
      cout << endl;
   }
    return 0;
}

Output

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

In this program, the outer loop iterates from 1 to rows.

The inner loop iterates from 1 to i. Inside the inner loop, we print the character '*'.

  • Note: There is no rule that a loop must be nested inside its own type. In fact, there can be any type of loop nested inside any type and to any level.
  • If you don’t understand above example, We recommended you to know little more about Nested Loop.

Ranged Based for Loop

In C++11, a new range-based for loop was introduced to work with collections such as arrays and vectors. Its syntax is:

for (variable : collection) {
    // body of loop
}

Here, for every value in the collection, the for loop is executed and the value is assigned to the variable.


Example 5: Range Based for Loop

#include <iostream>
      
using namespace std;
      
int main() {
        
    int num_array[] = {1, 2, 3, 4, 5};
        
    for (int n : num_array) {
        cout << n << " ";
    }
    return 0;
}

Output

1 2 3 4 5

In the above program, we have declared and initialized an int array named num_array. It has 5 items.

Here, we have used a range-based for loop to access all the items in the array.

If you didn’t understand the above example, don’t worry we will discuss about Array in later Tutorials.


C++ Infinite for loop

If the condition in a for loop is always true, it runs forever (until memory is full). For example,

// infinite for loop
for(int i = 1; i > 0; i++) {
// block of code
}

In the above program, the condition is always true which will then run the code for infinite times.

Exercise Files
No Attachment Found
No Attachment Found
error: Content is protected !!