Loops are generally used when a block of code needs to be executed repeatedly. It consists of a sequence of code that is executed and repeated until a specific condition is achieved. 

Iteration and Looping in C++

For example, if you would like to write a program that prints the word “Hello” 5 times, there are two ways to do it, either by writing 5 print statements or by using loops as can be seen in the next code snippet.

 

Alternative 1

#include <iostream>
using namespace std;

int main()
{
    cout << "Hello" << endl;
    cout << "Hello" << endl;
    cout << "Hello" << endl;
    cout << "Hello" << endl;
    cout << "Hello" << endl;

    return 0;
}

Output:

Hello

Hello

Hello

Hello

Hello

 

Alternative 2

#include <iostream>
using namespace std;

int main()
{
    for(int i=0; i<5; i++)
    {
        cout << "Hello" << endl;
    }

    return 0;
}

Output:

Hello

Hello

Hello

Hello

Hello

 

As you can see, both methods have exactly the same output. However, as your program gets more complex, for example if you want to print the word “Hello” 1000 times this time, writing 1000 print statements would not be wise or efficient.

For Loops

The for loop is typically used when you know exactly how many times or iterations should be executed. Generally, it enables you to execute your block K number of times using just one line of code.

Syntax

for (initialize iterator; end condition; iterator update)
{
    // block of code to execute
}

In for loops, the iterator or loop variable is used to control your loop. In other words, it is used as your counter, you choose what to do with it at each iteration (increment it or decrement by a certain amount) and finally decide when to end your loop when a specific condition is reached.

Example

Write a program that initializes an empty vector of integers and then fill it with numbers from 1 to 5000 using for loop.

Here we want to initialize the loop counter “i”, increment the counter with 1 at each iteration and pass it to the vector, and finally when the counter reaches 5000 breaks from the loop.

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<int> my_vect;
    for(int i=1; i<=5000; i++)
    {
        my_vect.push_back(i);
    }

    return 0;
}

Now we have executed a block of code 5000 times using only one code statement. 

While Loops

The difference between while and for loops is that this time you only need the end condition. This means, you need to handle the initialization of your iterator and incrementing or decrementing it separately and independent from the loop control statement.

Syntax

while (end condition)
{
    // block of code to execute
}

Example

Write a program that initializes an empty vector of integers and then fills it with numbers from 1 to 5000 using while loop.

Here we are going to implement the same program as in the loop however this time using while loop.

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector<int> my_vect;
    int i=1;

    while(i<=5000)
    {
        my_vect.push_back(i);
        i++;
    }

    return 0;
}

Note that in both examples, the for and while loops, you can choose to inversely loop from a greater to a smaller value and you can also increment your iterator using different values other than 1.

Example

Write a program that initializes an empty vector, fills it with only even numbers from 5000 to 1 using for loop.

Here we need to inversely loop from 5000 to 1 and decrement our iterator with value 2 to get only even numbers.

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector<int> my_vect;
    for(int i=5000; i>=1; i-=2)
    {
         my_vect.push_back(i);
    }

    return 0;
}

Do While Loop

The do-while loop is very similar to the while loop. However, in the do-while loop, the block of code is executed first before checking the end statement. 

Syntax

do
{
    // execute block of code
}
while (end condition);

Also, note that here we add a semicolon “;” at the end of the loop.

Example

Write a program to manually print characters in a string until the space character is found then the loop terminates.

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string hello = "Hello World!";
    cout << "Original String: " << endl;
    cout << "New String: ";

    int i=0;
    do
    {
        cout << hello[i];
        i++;
    }
    while (hello[i] != ' ');
    
    cout << endl;
    return 0;
}

Output:

Original String: Hello World!

New String: Hello 

Infinite Loops

Infinite loops are used when you need to execute a block of code forever and are typically used with embedded systems applications. On the other hand, they can be used for normal day to day applications and can normally be interrupted using break statements.

There are 2 ways to write infinite loops.

Method 1 

Writing an empty for loop control statement.

for(;;)
{
    // run forever
}

Method 2

Using and always TRUE condition with while loops.

while (true)
{
    // run forever
    while (1)
    {
        // run forever
    }
}

Example

Write a program that runs infinitely until and reads input characters from the user until the key button is hit. Definitely a better way to do this is using the getline function “std::getline(cin, line);”. However, an infinite loop is used here just for illustration. 

#include  <iostream>
#include  <string>
#include  <vector>
using  namespace  std;

int  main()
{
    string  myStr;
    char  c;

    cin  >>  std::noskipws;
    while  (cin  >>  c  &&  c  !=  '\n')
    {
        myStr.push_back(c);
    }

    cout  <<  myStr  <<  endl;
    return  0;
}

Range-based For Loops

Range-based for loops were introduced starting C++ 11. In this type of loops, we do not rely on counting values in our structure but instead, we loop over a range. 

For example, if you have a vector of integers, instead of creating a counter and then using this counter at each iteration to access an element in the vector, a range-based for loop would allow you to directly get that element without needing to count.

Example

Write a program that loops over a string and print “Found it” when character “W” is found (upper or lower case), print the index where it found it.

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string hello = "Welcome to the world wide web";
    int index = 0;

    for (char c: hello)
    {
        if ( (c == 'W') || (c == 'w') )
        {
            cout << "Found it at index: " << index << endl;
        }
        index++;
    }

    return 0;
}

Output:

Found it at index: 0

Found it at index: 15

Found it at index: 21

Found it at index: 26

Alternatively, range-based loops can be used more generically if you do not the type of iterator or what you are looping over by using the type inference “auto” in C++11.

Example

Write a program that initializes a vector and a string then loop over both and prints their elements.

#include <iostream>
#include <string>
#include <vector>
using  namespace  std;

int  main()
{
    string  myStr  =  "Hello  World!";
    vector  <int>  myVect  =  {1,2,3,4,5};

    for(auto  element:  myStr)
    {
        cout  <<  element;
    }
    cout  <<  endl;

    for(auto  element:  myVect)
    {
        cout  <<  element;
    }
    cout  <<  endl;

    return  0;
}

Output:

Hello World!

12345

“for_each” Loop in C++11

This one is similar in concepts to the looping techniques that we’ve discussed previously. However, here you are able to pass functions to the loop statement.

Note that this time you need to include one extra header:

#include <algorithm>

Syntax

for_each (InputIterator start, InputIterator end, Function fn)

This line can be interpreted to, for each element in memory from “start” iterator to “end” iterator, call the function “fn” and pass it the current iterator.

Example

Write a program that initializes an array of 10 integers, write a function that takes one integer as argument and prints it and then finally loops the array and print its elements using “for_each”.

#include  <iostream>
#include  <algorithm>
using  namespace  std;

void  printNum(int  num)
{
    cout  <<  num  <<  endl;
}

int  main()
{
    int  myArray[10]  =  {1,  2,  3,  4,  5,  6,  7,  8,  9,  10};

    for_each(myArray,  myArray  +  10,  printNum);

    return  0;
}

Output:

1

2

3

4

5

6

7

8

9

10

Here we used the start iterator as the first element in the array and the end iterator as the start iterator plus the size or number of iterations needed. Also, note that functions used need to be of type void.