Skip to main content

Control Flow

for Loop

We just discussed about while loop in C++ in the previous article. Now we're going to discuss for loops in C++.

Syntax

for (initialization; boolean_expression; update) {
    // statement(s)
}

How does this work?

  • Initialization is where we decide where to start counting. We set a variable like 'count' and give it a starting value, for example, 'count = 1.'
  • Boolean Expression is like deciding when to stop counting. We set a condition, like 'as long as count is less than or equal to 10.'
  • Update tells us how much to count up after each step. We increase our 'count,' for instance, 'count++' to add 1 every time.
  • Inside the curly braces '{ }', we write the actual steps or actions we want to happen during each iteration (loop cycle).

This might look a bit confusing. No worries! We've got you. Let's understand this with an example.

#include <iostream>
using namespace std;

int main() {
    for (int i = 1; i <= 3; ++i) {
        cout << "C++ is fun and easy to learn! " << endl;
    }

    return 0;
}
C++ is fun and easy to learn! 
C++ is fun and easy to learn! 
C++ is fun and easy to learn! 
Explanation:
Here's a breakdown of your code's execution:

    Initialization Expression: You start by setting a variable 'i' to 1.
    Boolean Expression: The loop checks if 'i' is less than or equal to 3. If 'i' is 1, this condition is true.
    Update Expression: After each iteration, '++i' increases 'i' by 1.

Now, let's see what happens in each iteration:

    Iteration 1:
        'i' is 1, and 'i <= 3' is true, so the print statements are executed.
        '++i' increases 'i' to 2.

    Iteration 2:
        'i' is 2, and 'i <= 3' is true, so the print statements are executed again.
        '++i' increases 'i' to 3.

    Iteration 3:
        'i' is 3, and 'i <= 3' is true once more, so the print statements are executed.
        '++i' increases 'i' to 4.

    Iteration 4:
        'i' is now 4, and 'i <= 3' is false, so the loop terminates.

Quiz

How many times will a 'for loop' with the following initialization, condition, and update expressions run?

for (int i = 1; i <= 5; i++){...}

Some Cool Examples

Using a for loop to print numbers from a to b (a and b are given by the user as inputs).

#include <iostream>
using namespace std;

int main() {
    int a, b;

    // Input 'a' and 'b' from the user
    cout << "Enter the starting number (a): ";
    cin >> a;
    cout << "Enter the ending number (b): ";
    cin >> b;

    cout << "Numbers from " << a << " to " << b << ":" << endl;

    // Use a 'for' loop to print numbers from 'a' to 'b'
    for (int i = a; i <= b; i++) {
        cout << i << " ";
    }

    return 0;
}
Explanation:

Here's how the code works:

1. We prompt the user to input 'a' and 'b' and read the values using `cin`.
2. We display a message indicating the range of numbers we're going to print.
3. We use a 'for' loop to iterate from 'a' to 'b'. The loop's initialization sets 'i' to the value of 'a', and it continues as long as 'i' is less than or equal to 'b'.
4. Inside the loop, we print the current value of 'i' followed by a space.
5. The loop runs through all the numbers in the range from 'a' to 'b'.
6. The program terminates, and the numbers from 'a' to 'b' are displayed.

Follow up : print in reverse from b to a from the previous problem.

Solution code
#include <iostream>
using namespace std;

int main() {
    int a, b;

    // Input 'a' and 'b' from the user
    cout << "Enter the starting number (a): ";
    cin >> a;
    cout << "Enter the ending number (b): ";
    cin >> b;

    cout << "Numbers from " << b << " to " << a << ":" << endl;

    // Use a 'for' loop to print numbers from 'a' to 'b'
    for (int i = b; i >= a; i--) {
        cout << i << " ";
    }

    return 0;
}

Factorial Calculation

#include <iostream>
using namespace std;

int main() {
    int n;
    int factorial = 1;

    // Input the number 'n' from the user
    cout << "Enter a positive integer: ";
    cin >> n;

    // Check for negative input
    if (n < 0) {
        cout << "Factorial is not defined for negative numbers." << endl;
    } else {
        // Calculate the factorial using a 'for' loop
        for (int i = 1; i <= n; i++) {
            factorial *= i;
        }

        // Display the result
        cout << "Factorial of " << n << " is " << factorial << endl;
    }

    return 0;
}
Explanation

We check if 'n' is negative. If it is, we inform the user that factorial is not defined for negative numbers.

If 'n' is non-negative, we proceed to calculate the factorial using a 'for' loop. The loop iterates from 1 to 'n', and in each iteration, it multiplies the 'factorial' by the current value of 'i'.

After the 'for' loop, we display the result, which is the factorial of 'n'.

Counting digits in a number

#include <iostream>
using namespace std;

int main() {
    int number, count = 0;

    // Input an integer from the user
    cout << "Enter an integer: ";
    cin >> number;

    // Handle negative numbers
    if (number < 0) {
        number = -number; // Make it positive
    }

    // Count the digits using a 'for' loop
    for (; number > 0; number /= 10) {
        count++;
    }

    // Display the count
    cout << "The number of digits is: " << count << endl;

    return 0;
}
Explanation

Here's how the 'for' loop works in this program:

We didn't initialize anything in the 'for' loop's initialization part, but we are using the existing variables.

- We start by checking if the 'number' is greater than 0. If it is, we enter the loop.

- After each iteration, we update 'number' by dividing it by 10. This removes the last digit from 'number,' bringing us closer to zero.

- We also increment the 'count' by 1 in each iteration inside the 'for' loop. This keeps track of how many digits we've counted so far.

- The loop continues until 'number' becomes 0, which means we have counted all the digits.

We use the 'for' loop without a traditional initialization because we are utilizing the existing values. The update part, dividing 'number' by 10, is crucial for counting each digit. When 'number' reaches 0, the loop terminates, and we display the count of digits.

Introducing Nested for Loops

By now, you're familiar with the power of 'for' loops, which are like magic wands in the world of coding. They help us repeat actions. But here's where things get even more exciting: nested 'for' loops!

Think of nested 'for' loops as loops within loops, just like a set of Russian nesting dolls where each doll contains another. 🪆🪆🪆

Let's understand this with an example,

#include <iostream>
using namespace std;

int main() {
    for (int i = 0; i < 3; i++) { // Outer loop: Controls rows
        for (int j = 0; j < 5; j++) { // Inner loop: Controls columns
            cout << "* ";
        }
        cout << endl; // Move to the next row
    }

    return 0;
}

Output

* * * * *
* * * * *
* * * * *
Explanation:
Step-by-Step Execution:

    1. The outer loop, controlled by i, starts with i = 0.

    2. Inside the outer loop, the inner loop, controlled by j, starts with j = 0.

    3. The inner loop prints a star (*) and increments j to 1.

    4. The inner loop continues, printing stars and incrementing j until j reaches 5.

    5. After printing 5 stars, the inner loop exits, and the program moves to the next line (row) by executing cout << endl;.

    6. The outer loop checks if the condition i < 3 is still true. If true, it increments i to 1 and starts the inner loop again.

    7. The inner loop repeats the process of printing stars in a row and moving to the next line for each row created by the outer loop.

    8. This continues until the outer loop completes three iterations, creating three rows.

Summary:

In summary, this code uses nested 'for' loops to create a rectangular pattern of stars.
The outer loop controls the number of rows (3 in this case), and the inner loop controls
the number of stars in each row (5 in this case).

Pattern Printing Problems

The output should look like :

let's say the input n = 6

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

Hence, you're basically required to ask user n as input and print n rows having the above pattern.

#include <iostream>
using namespace std;

int main() {
    int n;
    cout << "Enter the number of rows: ";
    cin >> n;

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

    return 0;
}
Explanation:
- The program starts by asking the user for the number of rows, denoted as 'n.'

- It uses a 'for' loop to iterate from 1 to 'n' to control the number of rows.

- Inside the loop, there is another 'for' loop that prints stars ('*') for each row, and the number of stars on each row matches the row number.

- After printing the stars for a row, the program moves to the next row by using `cout << endl;`.

- This process continues until 'n' rows are printed, creating a pattern with increasing stars on each row.

The result is a pattern of stars that grows from one star in the first row to 'n' stars in the last row, based on the user's input.

Reverse Right-Angled Triangle

The output should look like :

let's say the input n = 6

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

Hence, you're basically required to ask user n as input and print n rows having the above pattern.

#include <iostream>
using namespace std;

int main() {
    int n;
    cout << "Enter the number of rows: ";
    cin >> n;

    for (int i = n; i >= 1; i--) {
        for (int j = 1; j <= i; j++) {
            cout << "* ";
        }
        cout << endl;
    }

    return 0;
}
Explanation:
Basically we just had to reverse the outer loop from the previous pattern problem. 
Why?
This is because now we are needing n stars on the first row, n-1 on second...n-(i-1) on ith row.

Half Diamond

The output should look like :

let's say the input n = 5

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1

So how do we do this?
Hint : this task is a combination of the other two tasks that we just did before this.

#include <iostream>
using namespace std;

int main() {
    int n;
    cout << "Enter the number of rows: ";
    cin >> n;

    // the first top half, similar to the first task of pattern printing
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= i; j++) {
            cout << j << " ";
        }
        cout << endl;
    }

    // the second half, similar to the second task of pattern printing
    for (int i = n - 1; i >= 1; i--) {
        for (int j = 1; j <= i; j++) {
            cout << j << " ";
        }
        cout << endl;
    }

    return 0;
}
Explanation:
The program takes input from the user for the number of rows, denoted as 'n.'

It uses a 'for' loop to create the top half of the pattern. In each row, it prints numbers from 1 to 'i,' where 'i' represents the current row number.

After completing the top half, the program uses another 'for' loop to create the bottom half of the pattern, decrementing the row number.

The result is a pattern of numbers forming a half diamond, increasing from 1 to 'n' and then decreasing back to 1. The pattern is created with 'n' rows, where 'n' is the number of rows input by the user.

Hopefully, you enjoyed and learned a lot through this post.

Let's move to our final quiz problem.


Quiz

What will be the output of the following C++ program?

#include <iostream>
using namespace std;

int main() {
    for (int i = 1; i <= 5; i++) {
        for (int j = 5; j > i; j--) {
            cout << "  ";
        }
        for (int k = 1; k <= i; k++) {
            cout << k << " ";
        }
        cout << endl;
    }

    return 0;
}