简体   繁体   中英

How to skip last iteration of while loop in java?

This is my code:

System.out.println("Enter upper limit of range");
long u = in.nextLong(), x = 0, y = 1, z = x+y;
System.out.println("Fibonacci Series till " + u + " -");
System.out.print(x + " " + y + " " + z + " ");
while (z < u) {
    x = y;
    y = z;
    z = x + y;
    System.out.print(z + " ");
}

I want to skip the last iteration so that the last number of output does not go beyond the limit.

For example, if I initialise the value of u to 25 , then it will also print 34 which goes out of the limit. Skipping the last iteration will not display the number 34 .

Just print before you increment z to the next number in the Fibonacci sequence:

while (z < u) {
    System.out.print(z+" ");
    x = y;
    y = z;
    z = x + y;
}

With this change, the final iteration still would result in z being advanced to a value which is too high, and would fail the next iteration, but you would not be printing this number.

This refactor also takes care of another problem you had, namely not printing the first number in the Fibonacci sequence. By placing the print statement after advancing the number, the initial value of z would never have a chance to be printed.

how about:

while(z<u)
 {
    x=y;
    y=z;
    z=x+y;
    if (z < u) {
     System.out.print(z+" ");
    }
}

It's the simplest solution, assuming I got the question right...

while (...) {
   ...
   ...
   if (condition){
      continue; // which skips to the following iteration
      // or
      // break; // which just stops the loop from iterating
}

so the condition in your case could be z<u or you can put the print itself in the if clause

Print the current value first, then update z.

System.out.println("Enter upper limit of range");
long u=in.nextLong(),x=0,y=1,z=x+y;
System.out.println("Fibonacci Series till "+u+" -");
System.out.print(x+" "+y+" ");
while(z<u)
{
    System.out.print(z+" ");
    x=y;
    y=z;
    z=x+y;
}
System.out.println("Enter upper limit of range");
long u = in.nextLong(), x = 0, y = 1, z = x+y;
System.out.println("Fibonacci Series till " + u + " -");
System.out.print(x + " " + y + " " + z + " ");

while (true) {
    x = y;
    y = z;
    z = x + y;
    if(z>u) {
        break;
    }
    System.out.print(z + " ");
}

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