C++ Code Example: nested for loop

In the following program, a nested loop is used to check how often the loops are run through.

The program declares four integer variables: a, b, c1, and c2. a and b are set to 6 and 8, respectively. c1 and c2 are both set to 0 and will be used to keep track of the number of times each loop runs.

The outer loop, for (int i = 10; i > a; i--), starts with i equal to 10 and decrements i by 1 until i is no longer greater than a. So, this loop runs 4 times. Each time the outer loop runs, c1 is incremented by 1, so c1 will equal 4 after the outer loop has finished running.

The inner loop, for (int j = 0; j < b; j++), starts with j equal to 0 and increments j by 1 until j is no longer less than b. So, this loop runs 8 times for each iteration of the outer loop. Each time the inner loop runs, c2 is incremented by 1, so c2 will equal 32 after both loops have finished running (4 * 8 = 32).

The if (i == j) statement is checking if the values of i and j are equal. However, this condition will never be true because the outer loop decrements i while the inner loop increments j, so they will never have the same value.

Finally, the program outputs the results to the console using cout and returns 0, indicating that the program has executed successfully.

#include &lt;iostream&gt;
using namespace std;

int main() {
    int a = 6, b = 8, c1 = 0, c2 = 0;

    for (int i = 10; i > a; i--) {
        for (int j = 0; j < b; j++) {
            if (i == j) {
                cout << "How many times the loops are run?" << endl;
                cout << "first loop: " << c1 << "\nsecond loop: " 
                     << c2 << " (" << c1 << " * " << b << ")\n" << endl;

    return 0;
How many times the loops are run?
first loop: 4
second loop: 32 (4 * 8)