This code is written in Java and defines a class called NestedLoop
. It contains a single main
method that performs two nested for loops and counts the number of times each loop runs.
The outer for loop (for (int i = 20; i > a; i--)
) starts from i = 20
and decrements i
by 1 until it becomes less than or equal to a
. The inner for loop (for (int j = 0; j < b; j++)
) starts from j = 0
and increments j
by 1 until it becomes less than b
.
The two counters c1
and c2
keep track of the number of times each loop runs. The inner loop increments the value of c2
by 1 each time it runs. The outer loop increments the value of c1
by 1 each time it completes. The condition if (i == j)
checks if the current value of i
is equal to the current value of j
. If this condition is true, the program prints a message indicating the number of times each loop has run, along with the calculation of the total number of times the inner loop runs (c1 * b
).
class NestedLoop {
public static void main(String[] args) {
int a = 5, b = 7, c1 = 0, c2 = 0;
for (int i = 20; i > a; i--) {
c1++;
for (int j = 0; j < b; j++) {
c2++;
if (i == j) {
System.out.println("How many times the loops are run?");
System.out.print("first loop: " + c1 + "\nsecond loop: "
+ c2 + " (" + c1 + " * " + b + ")");
}
}
}
}
}
How many times the loops are run?
first loop: 15
second loop: 105 (15 * 7)