Creative Username Creative Username - 1 month ago 14
Java Question

Is there a way to count iterations using a while loop?

Is there a way in which the program can count the number of iterations in which it took for the variable "

counter
" to reach its limit? I'm writing a basic program that demonstrates the use of a while loop and have been asked to display the number of iterations which have been printed out.

P.S. Sorry if there are any errors in the indentation/formatting of the code, I'm new to Java/programming. Thanks in advance.

public class Main {
public static void main(String[] args) {
for (int counter=2; counter<=40; counter+=2) {
System.out.println(counter);
}
System.out.println("For loop complete.");

int counter = 1;
while (counter <= 500) {
System.out.println(counter);
counter++;
}
}
}

Answer

Just added a counter variable to track the loop execution count.

package main;
public class Main {
public static void main(String[] args) {
    for (int counter=2; counter<=40; counter+=2) {
       System.out.println(counter);
    }
    System.out.println("For loop complete.");

    int counter = 1;
    int loopExecCounter = 0;
    while (counter <= 500) {
        loopExecCounter = loopExecCounter + 1;
        System.out.println(counter);
    counter++;
    }
System.out.print(loopExecCounter);
 }
}

Hope this helps!

Comments