Skip to content Skip to sidebar Skip to footer

C++ For Loop – Learn C++ Programming

The looping statements are the most crucial concept to manipulate the program in the programming language. As we know, in this blog, we’re going to learn about C++ for loop. Conditional statements are significant in providing direction to the program and maintaining the programming flow. Similarly, Looping statements also play a crucial role in iteration and the number of times a program is supposed to be executed. We wouldn’t be able to execute advanced programs without loops. Here’s a quick geeky brief about loops:

  • Looping means repeating a block of code until the condition is satisfied.
  • Looping is also a part of control flow statements and conditional statements.
  • In the conditional statements, we enter the block which satisfies the condition.
  • In loops, the code enters the loop block and executes the line of codes repeatedly when the existing condition is already true with the loop condition, then exit the block when the condition is satisfied (turns false).
  • There are mainly three types of loopsfor loop, while loop, and do while loop.

This blog mainly focuses on one significant type of loop with its various subtypes, i.e., for loops; hence, let’s dive deeper by understanding what exactly these for loops are and how they work.

This is one of the best and the most detailed blog written by the author,i.e., “Kritish” (me), to date. This could also be the best C++ for loop blog on the web. So please read this C++ for loop blog carefully and like (heart button on the bottom) and comment about the blog on our website.

For Loops

For loop is one of the essential loops in any programming language. It is also one of the most used loops in the programming arena. For loop iterates and repeats the piece of code, along with a special variable called “the iterator.”

There are various subtypes of the for loops that we’re going to study in this blog tutorial. Hence it is the most extensive blog on the for loops on the internet. We will cover: For loop, Range-Based For Loop (for-each loop), and Infinite For Loop. All topics will be covered in detail with examples, outputs, syntax, diagrams, programs, and more.

IMPORTANT NOTE: In this blog, some terms are used, like the condition is satisfied and the condition is not. We want to provide some extra clarity on that for better understanding.

  • If the condition is not satisfied, that means the condition is returning true with the situation, or the program flow is turning out to be true with the condition, which means the program flow will enter inside the code block to iterate through the loops statement and satisfy the condition again and again until the condition turns out to be false.
  • Suppose the condition turns out to be satisfied. In that case, it means the condition is returning false with the situation, or the program flow is turning out to be false with the condition, which means the program flow will not enter the code block as the condition is already satisfied; therefore, it will skip the loop and continue the remaining program flow.

The Iterator

The iterator explanatory breakdown
The iterator explanatory breakdown

The iterator usually keeps track of the execution times of the code and the remaining execution times left,i.e., the iterator keeps track of how many times the code has been executed in the loop. And how many times it has to execute again to satisfy the condition.

The scope of the iterator is always inside the for loop block. Outside the for loop block, the variable has no scope of existence.

Diagram

The C++ For Loop Diagram
The C++ For Loop Diagram

Explanation

Let’s understand the for loop diagram efficiently in the geeky style:

  • Firstly, the flow of the program is encountered with the condition which decides whether the program is supposed to enter into the loop block or it shall skip it.
  • If the condition is true, the program will enter the for loop and execute all the loop statements until the end of the loop body.
  • Then the iterator will update its value, the updation of the iterator is subject to either increment or decrement, but in most cases, we use increment by default. And in this diagram, we’re assuming we’re using a post-increment in the iterator.
  • After iterator updation, we again check the condition of the for loop; if the condition is satisfied, the loop will be terminated, and the remaining program flow will continue to execute. Otherwise, the flow, again and again, returns to the loop body until and unless the loop condition gets satisfied.

Syntax

for (iterator initialization; condition; iterator update){
  // Code Block to be executed in the loop
}
C++

Explanation

Decoding the Syntax:

  • Firstly, for function is used with its functions parameters as part of the syntax,i.e., for().
  • Then the iterator is initialized; remember, the iterator is nothing but a simple integer variable inside the scope of the loop body.
  • Then, the simple condition has to be provided as the base of the loop, as the loop with process the program to satisfy the condition.
  • Then the iterator update is there; it can be an increment or decrement. In advanced scenarios, programmers also use pre-increment/decrement instead of post-increment/decrement. But the post-increment is the most common form of iterator update.

Example 1: Displaying “Geeky Time” n number of times.

#include <iostream>
using namespace std;

int main(){
    int times;
    cout<<"Enter Times: ";
    cin>>times;
    for (int i=0; i<times ;i++){
        cout<<"Geeky Time"<<endl;
    }
    
    return 0;
}
C++

Output

The output of C++ For Loop Example 1
The output of C++ For Loop Example 1

Explanation

Let’s understand the logic and the mystery behind this little code:

  • Here, we’re beginning with taking user input on the number of times the word “Geeky Times” has to be printed on the screen.
  • Then simply, we’re initializing the iterator at 0 and the condition where the iterator will loop the code block until it reaches the target (excluding the target as there is no = sign). However, the iteration times will be accurate as the iterator starts from 0; hence 0 will be included. For example, if we enter 8, it will run from (0-7), i.e., 0,1,2,3,4,5,6,7, therefore 8 iterations.
  • In the third step, the iterator is incremented.
  • Inside the body, the “Geeky Time” will be printed n number of times as specified, and the condition will execute until satisfaction.

Example 2: Printing numbers in counting order until the target

#include <iostream>
using namespace std;

int main(){
    
    int target;
    cout<<"Enter Target: ";
    cin>>target;
    
    for (int i=1;i<=target;i++){
        cout<<i<<endl;
    }
}
C++

Output

The output of C++ For Loop Example 2
The output of C++ For Loop Example 2

Explanation

Let’s understand how this program works and the logic used behind the code:

  • Firstly, we’ve initialized the target variable and will store the target until the number is printed.
  • Then, the program will take the input of the target from the user, which is pretty simple.
  • Here, the ultimate game begins; the for loop is taken into use by the first initialization of the iterator to 1.
  • In the condition part of the for loop structure, the condition is set to be until the iterator is less than and equal to the target, i.e., the loop will constantly run until the iterator is smaller than and equals the target and will satisfy after the target becomes greater than the target. Therefore the numbers will be executed until the target, and after the iterator becomes greater, the condition turns out to be false (satisfied). Hence terminated.
  • In the third part of the for loop structure, we increment the iterator and execute the loop body.
  • Inside the loop body, we print the current value of the iterator.
  • For example, in the first case, the iterator’s value is 1. It goes back to the condition, and if it’s not satisfied, the value becomes 2, hence printed 2; again, it will go and check the condition, increment, print, and the process will continue until the satisfaction of the condition.

Range-Based For Loop

Range-Based for loop is another one of its kind loop in the for loop category. It is also known as the for-each loop in C++. Range-Based for loop/for-each loop was introduced in C++11. It is used for efficiently looping and iterating over a collection of elements, such as arrays, vectors, or a list.

The Range-Based For loop/For-each loop works by iterating through an array or a container and extracting the elements of that collection one at a time. The syntax of the range-based for loop is similar to the normal for loop; however, it is much more efficient and easier to work with.

Syntax

for (iterator : collection){
    //loop body
    }
C++

Explanation

The range-based for loop has a straightforward explanation:

  • Firstly, we need an iterator or the loop variable just like we need in for loop, corresponding to the collection, which can be an array, vector, or list. These three can are usually referred to as the collection.
  • Then, we must enter the commands to execute in the loop body.
  • In this scenario, the for loop will automatically iterate until the end of the collection.

Example: Iterating Array Elements

#include <iostream>
using namespace std;

int main() {
    int arr[]={9,8,1,1,3};
    for (int i : arr){
        cout<<i<<endl;
    }
    return 0;
}
C++

Output

The output of the Range-Based loop
The output of the Range-Based loop

Explanation

Let’s understand now what’s brewing in the range-based for loop’s code right here quickly:

  • Starting with the array, we’re creating an array of 5 numbers with array elements as 9,8,1,1,3.
  • The Range-Based loop is implemented on the following line in which one side has the iterator, and on with right, it has the array name.
  • Inside this for-loop iteration, it will automatically iterate till the end of the collection, in our case,i.e., the array.
  • Inside the loop body, we have the array elements to be printed in the new lines until the loop iteration is completed.

Nested For Loop

The Nested for loop is simply a loop inside a loop. The inner loop can be used to execute multiple statements within the body of the outer loop. The inner loop executes all its iterations for each outer loop iteration. For example, when printing a multiplication table or solving the star pyramid questions.

Example: The MYSTERY of Pyramyd

#include <iostream>
using namespace std;

int main() {

    for (int i=1;i<=8;i++){
        for (int j=1;j<=i;j++){
            cout<<"*";
        }
        cout<<endl;
    }
 
}
C++

Output

The output of the Nested Loop
The output of the Nested Loop

Explanation

The above code could seem a little bit complex to newbies, but it’s also a piece of cake:

  • Inside the main function, there are 2 for loops, the inner loop, and the outer loop; the whole game is to understand the delicate working of both the for loops simultaneously.
  • Firstly, we must notice that 8 columns are printed in the output. This is courtesy of the outer for loop, which has been instructed to run from 1 to 8 with the iterator incrementing by 1, which is the default.
  • The main game is simultaneously working the inner and outer loops. We’ll get to the understanding step-by-step.
  • The inner loop has been instructed to run from 1 until the outer loop’s iterator. This precisely makes a pyramid shape, as the inner loop’s value steadily increases with each increment in the outer loop iteration. The inner loop prints the star in the output, and the number of stars printed in each row increases by 1 due to this increment.
  • Let’s understand what happens in this session ahead. Still, the significant part is that after each session of the inner for loop ends, an end-line statement gets printed just before the next session begins. This end-line statement separates the lines of the pyramid, making it possible to print like a pyramid.
Let's Understand it more practically.

In the first place, when (outer loop's iterator -> ) i is 1,
the (inner loop's iterator -> ) j also runs from 1 until 1, printing just the one *
Then, after one session of the inner loop, an end-line statement gets executed to get into the next line.

Similarly, when i becomes 2, in the second line, the j also becomes 1, then prints *, then j turns 2, and again it prints another star. Therefore ** in total.

End-line statement gets executed.

i becomes 3, and j prints run (1-2-3) and print 3 stars (1 in each turn) stars. *** in total.

And the program continues until 8 and terminates as both conditions are satisfied.
C++

Infinite For Loop

An infinite loop is a condition that iterates over and over indefinitely, as the loop condition never gets satisfied as per the flow of the program. In this situation, the program never gets executed entirely; programmers have to terminate the program flow manually to stop the execution of the program.

Most of the time, this situation occurs due to logical & programmatic errors or due to negligence of the programmer. Hence it’s an error scenario in most cases. But there are also some scenarios where we intentionally use an infinite loop; for example, I’m using it right now to teach you guys and make you aware of the infinite loops (XD).

In general programming, infinite loops should be avoided as they’re the error cases, and this blog is to make you aware of the infinite loops, so next time, you should know that you’re in trouble.

Example: The Geeky Uchiha’s Infinite Tsukuyomi

#include <iostream>
using namespace std;

int main(){
    for (int i = 0;i < 1;i--){
        cout<<"Geeky Time XD"<<endl;
        cout<<"Powered by GeekonPeak"<<endl;
        cout<<endl;
    }
    
    return 0;
}
C++

Output

The output of the Infinite Loop
The output of the Infinite Loop

Explanation

It’s super simple, simpler than baby shark du dudu dududu:

  • The Loop body itself has a flaw in itself; the iterator is initialized at 0, and the condition is the loop shall run until i is less than 1 and i is decrementing.
  • When i constantly decrement from 0 to -1,-2,-3, it will never be able to overcome the condition and will always remain less than 1 in any circumstance. Hence it will constantly iterate infinite times, hence an infinite loop or an endless loop.
  • The super-easy way to create an infinite loop is by not passing any parameter in for loops body; it also creates an infinite loop. I’ve used the above situation to explain to you so you can understand the real-time scenario. Otherwise, the super simple version of the infinite loop should look like this:
#include <iostream>
using namespace std;

int main(){
    for (;;){                          //Pay Attention no parameters here
        cout<<"Geeky Time XD"<<endl;
        cout<<"Powered by GeekonPeak"<<endl;
        cout<<endl;
    }
    
    return 0;
}
C++

Program 1: Sum of the First n Natual Even Numbers

#include <iostream>
using namespace std;

int main(){
    
    //Part 1: Initialization & Accepting Data
    
    int num;
    cout<<"Enter Number: ";
    cin>>num;
    int sum = 0;
    
    //Part 2: The Main Operation
    
    cout<<"The Positive Numbers --> "<<endl;
    
    for(int i=1; i<=num ; i++){
        if (i%2 == 0){
            cout<<i<<endl;
            sum +=i ;
        }
        else{
            continue;
        }
    }
    
    //Part 3: Printing The Total
    
    cout<<"The Total Sum: "<<sum;
    
    return 0;
}
C++

Output

The output of the first program featured in the C++ for loop blog
The output of the first program featured in the C++ for loop blog

Explanation

Note: Please make sure to code and run the program manually on onlinegdb for better practical exposure.

Objective: The program will take user input and print the even numbers and their sum until the user in their input provides the last even number.

Let’s get the ultimate explanation for the strange lines of code provided above:

  • In the first part, we initialized a variable “num,” accepted a value from the user, and stored it in the “num” variable.
    //Part 1: Initialization & Accepting Data
    
    int num;
    cout<<"Enter Number: ";
    cin>>num;
    int sum = 0;
C++
  • In the second part, we’ve put the for loop in which the iterator starts from 1, running until the number provided by the user, “num,” and incrementing by default,i.e., 1.
  • Inside the for loop, a conditional statement prints the number and adds the value to the sum only when the number is adequately divisible by 2 and leaves the remainder 0, which means an even number.
  • If the number is not divisible by 2, the number is passed into the else block with the continue statement. That means all odd numbers are passed in continue statements which skip the operation with the current number (current session), move on and continue the iteration with the next number.
  • Interpreting this, the if statement only considers the number and performs the printing and the addition operation if the number is an even number. Otherwise, any odd number will fall into the else block and be skipped from the operation; hence the program flow will get to the next number and perform the very same operation of the loop.
    //Part 2: The Main Operation
    
    cout<<"The Positive Numbers --> "<<endl;
    
    for(int i=1; i<=num ; i++){
        if (i%2 == 0){
            cout<<i<<endl;
            sum +=i ;
        }
        else{
            continue;
        }
C++
  • In the third part of the program, the total sum of the even numbers is printed. The individual numbers were printed during the iteration process; the total sum is printed at the end.
    //Part 3: Printing The Total
    
    cout<<"The Total Sum: "<<sum;
C++

Program 2: The Prime Number Checker

#include <iostream>
using namespace std;

int main(){
    
    //Part 1: Initialization & Accepting User Data
    
    int num;
    cout<<"Enter Number: ";
    cin>>num;
    bool prime = true;
    
    //Part 2: The Evaluation

    for (int i=2; i<num ;i++){
        if (num%i==0){
            prime = false;
            break;
        }
    }
    
    //Part 3: The Results
    
    if (prime){
        cout<<num<<" is a prime number!"<<endl;
    }
    else{
        cout<<num<<" is not a prime number!"<<endl;
    }
    return 0;
}
C++

Output 1: Not a Prime Number

Case 1 of the output of the second program featured in the C++ for loop blog
Case 1 of the output of the second program featured in the C++ for loop blog

Output 2: Prime Number 

Case 2 of the output of the second program featured in the C++ for loop blog
Case 2 of the output of the second program featured in the C++ for loop blog

Explanation

Note: Please make sure to code and run the program manually on onlinegdb for better practical exposure.

Objective: This program will take user input, evaluate and let you know whether the number entered by you is a prime number.

This code could feel a bit complex to the newbies, but you’ll have to get to complex code now to strengthen your coding journey:

  • In the first part, we initialize a variable named “num,” accept a user value, and store the value in “num.”
  • The exciting part here is we’ve also created a boolean variable named “prime,” which has been valued at “true.” This means we’re assuming that the number will be the prime number initially. But wait and let the actual game begin.
   //Part 1: Initialization & Accepting User Data
    
    int num;
    cout<<"Enter Number: ";
    cin>>num;
    bool prime = true;
C++
  • In the second part, the evaluation begins. Inside the for loop, the iterator begins from the value 2 and will go until the number provided by the user (excluding the number itself).
  • As we know, a prime number is any number that does not get divided from any number excluding the number 1 and the number itself. Therefore as per the definition of prime number, the for loop starts at 2 until the number itself (num variable) where the “num” is excluded.
  • In the first part, we’ve already presumed that our number is prime initially. Inside the for loop, we’re validating whether our number is prime or not.
  • As we already know, the iterator is running from 2 until the num and inside the if statement every time it is being checked whether the number “num” is getting divided by the iterator. This means it checks whether the number is divisible from 2 until the number less than the target number itself.
  • If the number does not get divided anywhere, the prime’s boolean value remains true, as the number is indeed a prime number; therefore, the loop is terminated.
  • If it gets divided anywhere, the value of the boolean variable prime is overridden to false. The break statement is executed to exit the loop and stop the iteration forcefully. The break statement is crucial as it terminates the loop right away.
    //Part 2: The Evaluation

    for (int i=2; i<num ;i++){
        if (num%i==0){
            prime = false;
            break;
        }
    }
C++
  • In the third part, the conditional statement awaits to declare the evaluation results. If the value of the prime variable remains true in the for loop, then the number will be printed as a prime number, as if the block will be executed.
  • Otherwise, if the value of the prime variable is changed to false, the else block will be executed, and hence the number will be printed as the non-prime.
    //Part 3: The Results
    
    if (prime){
        cout<<num<<" is a prime number!"<<endl;
    }
    else{
        cout<<num<<" is not a prime number!"<<endl;
    }
    return 0;
}
C++

Conclusion

In this blog, we’ve thoroughly gained knowledge of the loops and gone through the concepts of looping and iteration. The iterator and the for loop are the major topics covered in this video to extend the scope of the learners’ learning. The major subtypes of for loop, including range-based for loop/for-each loop, and nested for loop, are also included in this tutorial. We’ve also gone through the infinite loop issue and some real-life problems, programs, and scenarios that should help you to solve the framed interview questions.

In the upcoming blogs, you’ll get exposure to while loop, do-while loop, continue statements, and break statements. This will complete the entire tutorial series course for C++ beginners to intermediate. After the C++ beginners to intermediate, the geeks plan to expand the peak with more extensive tutorials to enhance the learning base and provide more exclusive and practical learning.

This is also one of the most detailed blogs ever, and it took a lot of money & effort to upgrade the blog’s quality to this level. We’ve just begun. We’ve constantly improved the quality to enhance your experience, which shall require your support, and we expect it from you.

We shall start accepting donations soon as we’re spending heavily on the maintenance and the super high-quality content creation & research of the website. You can now support us through the like button on the bottom, sharing this blog, disabling ad blockers, commenting on your thoughts, and connecting with us on socials.

You can also support us by visiting this blog and buying the reviewed services (They’re tested and the best in the market), which will help us grow, develop, and upgrade the content quality to the next level. You may also subscribe to our newsletters, check out our latest blogs from other niches, and hit a like (heart) below the blog. Perfect Goodbye for now, and enjoy the ever-best programming blog series only at GeekonPeak!

2 Comments

  • Sherril Eissinger
    Posted March 3, 2023 at 6:42 PM

    Thank You! Was good 🙂

    • Post Author
      Kritish
      Posted April 8, 2023 at 5:44 PM

      Thank you so much, Sherril, for such kind words 🙂

      We’ve prioritized solving the doubts first, But we also acknowledged your appreciation.

      We were glad to know that it helped you; you can share this tutorial and website with others to help us grow.

      Besides, don’t forget to subscribe to our newsletters, as amazing updates will be there on GeekonPeak Soon!

Leave a comment

Sign Up to Our Newsletter

Be the first to know the latest updates