While inside While (While principal stops)

Asked

Viewed 2,073 times

-1

I need to create two bonds going from 1 to 10, only one inside another.

WORKS

  • Using for and for.
  • Using while e for.

Why doesn’t it work?

1) WHILE AND WHILE

int a=1, b=1;

    while(a<=10) {          
        while(b<=10) {
            System.out.print(a + "-" + b + "  ");
            b++;
        } //fim while b
        System.out.println("");
        a++;
    }//fim while a

2) FOR E WHILE

int b=1;

    for(int a=1; a<=10; a++) {
        while(b<=10) {
            System.out.print(a + "-" + b + "  ");
            b++;                
        }// fim while b
    }// fim for a

2 answers

3


Your while -> while is working. He is correct.

The problem is that the condition of the second while (b<=10) will always be fake after the first loop, That’s because you’re adding 1 to the variable b and is not resetting its value, for example:

public class HelloWorld
{
  public static void main(String[] args)
  {
    int a=1, b=1;

    while(a<=10) {          
        while(b<=10) {
            System.out.print(a + "-" + b + "  ");
            b++;
        }
        System.out.println("");
        a++;
        b = 1; //Reseta o valor de "B"
    }
  }
}
  • 1

    Adding to your answer: In FOR loops, every time you iterate again through the loop, the variable starts again. What happens is that there is a new variable declaration in each loop iteration, and so its value is always updated (i++ uses i in the current value and adds +1 to the next statement) so in its declaration it is usually seen to be (int i = 0; i < x; i++).

3

Browser other questions tagged

You are not signed in. Login or sign up in order to post.