简体   繁体   中英

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.

PS 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++;
        }
    }
}

If I've understood your question correctly, you're looking for something to keep incrementing the value as part of the loop rather than as a separate statement. Well, you could make it more terse using the ++ operator.

int x = 0;

while(x++ < 100) {
    System.out.println(x);
}

Some Detail

x++ is shorthand for x = x + 1 . There is a slight caveat with this. x++ means return the value of x, then order it. So...

while(x++ < 100)

Will print out 0,1,2,3,4,5....99 (therefore iterating exactly 100 times) However, if you have ++x instead, this says to increment then return. So:

while(++x < 100)

would print out 1,2,3,4,5...99 (and iterate 99 times).

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM