Home C++ C++ for Loops with examples

C++ for Loops with examples

Before we hop into the tutorial, let’s try to imagine a situation. Consider a scenario where you want to print a statement 10 times. There are 2 options:

  • Either you write the statement 10 times 
  • Or you loop through the statement that sets the counter to 10

The latter is better because it reduces the lines of code. Professionally we write a lot of code; if loops didn’t exist, we would be left with large lines of repetitive code, which would be very frustrating for reading and writing the code.

Categories of Loops in C++

There are 2 categories of loops:

A Conditional Loop

The Loop keeps on executing until a particular condition exists and breaks if the condition becomes false. The catch in conditional loops is that you never know for how long the loop will keep on executing.

A Count-Controlled Loop

Sometimes you know exactly how many times your loop will execute. For example, you want to display the names and marks of 10 students; this is the situation where count-controlled loops come in handy.

Some basic features of count-controlled loops are as follows:

  • It should initialize a counter variable to a starting value
  • It should check the terminating condition 
  • It should update the counter variable after each iteration

What is a For Loop?

A for loop is simply a count-controlled loop. The for loop has a basic format as shown.

for (initialization; test; update) 
{ 
statement; 
statement;
}

The first line of the for loop is the loop header, and the lines inside the braces will execute multiple times depending on the test condition. The for loop is based on 3 expressions, each separated by a semicolon.

The first expression is the initialization statement. This expression is used to initialize a variable to a starting value and is executed only once.

The second expression is the test statement, which controls the loop’s execution and is evaluated; if the expression is true, the loop keeps on executing and stops executing once the condition becomes false.

The third expression is updated, which executes at the end of each iteration and updates the counter variable’s value.

Here is an example of how a for loop is executed:

#include<iostream>
using namespace std;
//Program demonstrating for loop
int main() {
	
	for(int i = 1; i <= 10 ;i++) 
    {

    cout<<"loop number: "<<i<<endl;
	}
}

int i = 1 performs the initialization and initializes the value of the counter variable to 1. Then the loop executes until the condition i<=10 becomes false, and the value of i increments for each iteration until the condition becomes false.

For Loop: A pretest loop

A for loop is a pretest loop. Now the question arises what is a pretest loop? A pretest loop evaluates its test condition before a loop executes i.e. it is possible for the loop to not iterate at all!

We can see this in action in the code below:

for(int i = 2; i < 1; i++) 
{
//statement
}

The value i = 2 makes the test condition false hence the loop is never executed.

Note: If there is only one statement in the loops body, then the braces can be omitted.

Common Mistakes when Dealing with Loops

Some mistakes are unintentional but can be very costly in terms of programming. A mistake that many new programmers make is terminating the loop. By terminating, I mean putting a semicolon at the end of the for statement. The semicolon separates the loop from the code written in the braces, and the line will execute just once.

for (int  i = 0; i < 10; i++); // mistake 
{
	 cout<<"HEY!!";
}

Another mistake is to modify the counter variable in the body of the for loop. The consequence of this mistake would be that the loop will not terminate when you expect it to.

An example below highlights this mistake:

for(int i = 0; i < 10; i++) 
{
  	cout<<i;
  	i++; // mistake
}

Nested For Loops

What is a nested loop? A nested loop is just a loop within a loop. Nested loops can be beneficial when accessing elements in 2D arrays. The code below shows the basic syntax of a nested for loop:

#include <iostream>
using namespace std;

int main()
{
  //To create 5 rows
    for(int i = 1; i <= 5; i++)
    {
        for(int j = 1; j <= i; j++)
        {
            cout << "* ";
        }
        cout <<endl;
    }    
}

The above code creates a right-angled triangle. The first for loop executes 5 times to print 5 rows of stars and the second loop runs until j<=i, so when the first loop runs for the first time, the value of i=1 and when the second loop runs for the first time, the value of j=1 thus the value of j=i, therefore, a single star is printed in the first row. The second loop is not executed for j=2 because j>i after the statement j++ executes; hence the second loop breaks, and the program flow goes to the first loop again. The picture shows the final result after both the loops have been executed.

pattern

Bad Programming Style

Omitting the for loop’s expressions and even the loop body is possible but is considered a bad programming practice. For example, the initialization can be done outside the loop, and the initialization portion can be left empty. The code for the example is shown below

#include <iostream>
using namespace std;

int main()
{
    int num = 1;
    int maxValue = 5;
	for ( ; num <= maxValue; num++)
	cout << num << " " << (num * num) << endl;
}

The above code will work perfectly fine, but a good practice would be to initialize the num variable inside the for loop header. Similarly, the increment value can also be done inside the loop body and excluded from the loop header. Moreover, the for loop can work just like the while loop, as shown in the example below.

#include <iostream>
using namespace std;

int main()
{
    int maxValue = 5;
	int num = 1;
	for ( ; num <= maxValue; )
	{ 
      cout << num << " " << (num * num) << endl;
	  num++;
	}
}

It is also possible to write a for loop without anybody i.e. if the logic is small, like printing 10 numbers, the whole thing can be done inside the loop as shown below:

#include <iostream>
using namespace std;

int main()
{
    for (int count = 1; count <= 10; cout << count++ <<" ");
}

All the examples shown in this section are just demonstrations of the variations found in the for loop. However, it is recommended not to use this style of programming until very necessary.

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More