Skip to content

Loops in C++

Loops are indented to repeat a block of codes as long as a condition is met. There are different forms of loops in C++.

while statement

The while loop repeats a block of code as long as a specified condition is true. The syntax is as follows.

while (condition){
    // code block to repeat
}

For example,

print-till-ten-with-while.cpp
#include <iostream>

using namespace std;

int main()
{
    int i = 1;
    while (i <= 10)
    {
        cout << i << endl;
        i++;
    }

    return 0;
}

do-while statement

The do-while loop is a variant of the while loop. This loop will at least execute the code block once. Then it will repeat the loop as long as the condition is true. The syntax is as follows.

do {
    // code block to repeat
}
while (condition);

For example,

print-num.cpp
#include <iostream>

using namespace std;

int main()
{
    int i;
    cout << "i is ";
    cin >> i;

    do
    {
        cout << i << endl;
        i++;
    } while (i <= 10);

    return 0;
}

Compile and execute the program above and see how the program responses given different input.

for statement

If we know exactly how many times you want to repeat a block of code, use the for loop is a good option. The syntax is as follows.

for (statement1; statement2; statement3) {
  // code block to repeat
}
  • statement1 is executed (one time) before the execution of the code block.
  • statement2 defines the condition for executing the code block.
  • statement3 is executed (every time) after the code block has been executed.

For example,

print-till-ten-with-for.cpp
#include <iostream>

using namespace std;

int main()
{
    for (int i = 1; i <= 10; i++)
    {
        cout << i << endl;
    }

    return 0;
}

break and continue

  • break can be used to have an early exit and jump out of a loop.
  • continue only breaks the current iteration and continues with next iteration in the loop.

For example,

test-flow.cpp
#include <iostream>

using namespace std;

int main()
{
    for (int i = 1; i <= 10; i++)
    {
        if (i % 2)
        {
            continue;
        }
        else if (i == 8)
        {
            break;
        }

        cout << i << endl;
    }

    return 0;
}

Assignment 6

Create a C++ program named square.cpp that prompts for length of a square. The program will then display a square of the given length in the terminal.

We can use any character to represent the side of a square. A sample run would look like the following.

g++ square.cpp -o square
./square
Enter length: 6
******
*    *
*    *
*    *
*    *
******
Sample Solution
square.cpp
#include <iostream>

using namespace std;

int main()
{
    int length;
    int c;
    cout << "Enter length: ";
    cin >> length;
    for (int row = 0; row < length; row++)
    {
        if ((row == 0) || (row == length - 1))
        {
            for (c = 0; c < length; c++)
            {
                cout << '*';
            }
            cout << endl;
        }
        else
        {
            cout << '*';
            for (c = 0; c < length - 2; c++)
            {
                cout << ' ';
            }
            cout << '*' << endl;
        }
    }
}

Assignment 7

Create a C++ program named odd-or-even.cpp that would keep prompting for a number and tell if that number is odd or even. The program exists if the user enters a negative number.

A sample run looks like the following.

g++ odd-or-even.cpp -o odd-or-even
./odd-or-even
Enter a number: 3
Odd number
Enter a number: 2
Even number
Enter a number: 1
Odd number
Enter a number: 0
Even number
Enter a number: -1
See you later!
Sample Solution
odd-or-even.cpp
#include <iostream>

using namespace std;

int main()
{
    int number;

    while (true)
    {
        cout << "Enter a number: ";
        cin >> number;
        if (number < 0)
        {
            cout << "See you later!" << endl;
            break;
        }
        else if (number % 2)
        {
            cout << "Odd number" << endl;
        }
        else
        {
            cout << "Even number" << endl;
        }
    }

    return 0;
}

Quote

practice

Assignment 8

Create a C++ program named print-triangle.cpp that prompts for rows of a triangle. The program will then display a triangle with the given number of rows in the terminal.

A sample run looks like the following.

g++ print-triangle.cpp -o print-triangle
./print-triangle
Enter number of rows for the triangle: 7
      *
     **
    ***
   ****
  *****
 ******
*******
Sample Solution
print-triangle.cpp
#include <iostream>

using namespace std;

int main()
{
    int row;
    cout << "Enter number of rows for the triangle: ";
    cin >> row;
    for (int i = 0; i < row; i++)
    {
        for (int j = row - i - 1; j > 0; j--)
        {
            cout << " ";
        }
        for (int k = 0; k < i + 1; k++)
        {
            cout << "*";
        }
        cout << endl;
    }

    return 0;
}

Assignment 9

Create a C++ program named diamond.cpp that prompts for rows of a diamond, where the number of rows shall be odd. The program will then display a diamond with the given number of rows in the terminal.

A sample run looks like the following.

g++ diamond.cpp -o diamond
./diamond
Enter number of rows: 21
          *
         ***
        *****
       *******
      *********
     ***********
    *************
   ***************
  *****************
 *******************
*********************
 *******************
  *****************
   ***************
    *************
     ***********
      *********
       *******
        *****
         ***
          *
Sample Solution
diamond.cpp
#include <iostream>

using namespace std;

int main()
{
    int row;
    while (true)
    {
        cout << "Enter number of rows: ";
        cin >> row;
        if (row % 2)
        {
            break;
        }
    }

    int i, j;

    // upper part
    for (i = 0; i < row / 2; i++)
    {
        for (j = 0; j < row / 2 - i; j++)
        {
            cout << " ";
        }
        for (j = 0; j < 2 * i + 1; j++)
        {
            cout << "*";
        }
        cout << endl;
    }

    // middle
    for (j = 0; j < row; j++)
    {
        cout << "*";
    }
    cout << endl;

    // bottom part
    for (i = row / 2 + 1; i < row; i++)
    {
        for (j = 0; j < i - row / 2; j++)
        {
            cout << " ";
        }
        for (j = 0; j < 2 * (row - i) - 1; j++)
        {
            cout << "*";
        }
        cout << endl;
    }

    return 0;
}

Assignment 10

Create a C++ program named plus.cpp that prompts for rows of a plus sign, where the number of rows shall be odd. The program will then display a plus sign with the given number of rows in the terminal.

A sample run looks like the following.

g++ plus.cpp -o plus
./plus
Enter number of rows for the plus: 11
     *
     *
     *
     *
     *
***********
     *
     *
     *
     *
     *
Sample Solution
plus.cpp
#include <iostream>

using namespace std;

int main()
{
    int row;
    while (true)
    {
        cout << "Enter number of rows for the plus: ";
        cin >> row;
        if (row % 2)
        {
            break;
        }
    }

    int i, j;

    for (i = 0; i < row; i++)
    {
        if (i != row / 2)
        {
            for (j = 0; j < row / 2; j++)
            {
                cout << " ";
            }
            cout << "*" << endl;
        }
        else
        {
            for (j = 0; j < row; j++)
            {
                cout << "*";
            }
            cout << endl;
        }
    }

    return 0;
}

Assignment 11

We can generate a random number with the help of cstdlib lib. See the following example for a random within 1 and 1000.

print-random-number.cpp
#include <iostream>
#include <cstdlib>

using namespace std;

int main()
{
    srand(time(0));

    int number = rand() % 1000 + 1;
    cout << "Random number is " << number << endl;

    return 0;
}

Create a C++ program named number-guessing-game.cpp that sets a random number (1 to 1000) for user to guess. It will display "Bingo!" if the user provides an exact match. If not, prompts the user if the number is higher or lower. Keep the game playing till the random number is provided.

A sample run looks like the following.

g++ number-guessing-game.cpp -o number-guessing-game
./number-guessing-game
Your guess is 500
It should be higher...
Your guess is 750
It should be lower...
Your guess is 625
It should be lower...
Your guess is 575
It should be lower...
Your guess is 535
It should be higher...
Your guess is 550
It should be higher...
Your guess is 560
It should be lower...
Your guess is 555
It should be lower...
Your guess is 553
It should be higher...
Your guess is 554
Bingo!
Sample Solution
number-guessing-game.cpp
#include <iostream>
#include <cstdlib>

using namespace std;

int main()
{
    srand(time(0));

    int number = rand() % 1000 + 1;

    int guess;
    while (true)
    {
        cout << "Your guess is ";
        cin >> guess;
        if (guess == number)
        {
            cout << "Bingo!" << endl;
            break;
        }
        else if (guess > number)
        {
            cout << "It should be lower..." << endl;
        }
        else
        {
            cout << "It should be higher..." << endl;
        }
    }

    return 0;
}