Search code examples
javawhile-loopnested-loops

nested while-loop that doesn't match the condition


I am trying to make a program that print the following numbers :

1 1
1 2
1 3
1 4
2 1
2 2
2 3
2 4

The code is

   public class JavaApplication8 {

    public static void main(String[] args) {

        int i = 1;
        int j = 1;

        while (i <= 2 && j <= 4) {

            while (i <= 2 && j <= 4) {

                System.out.printf("%d%d\n", i, j);

                j++;
            }

            j = j - 4;

            i++;

            System.out.printf("%d%d\n", i, j);
            j++;

        }

    }
}

The program prints this

1 1
1 2
1 3
1 4
2 1
2 2
2 3
2 4
3 1

I don't know why this is happening behind the condition inside while says that it i must be smaller or equal 2


Solution

  • It's outputting that final 3 1 because your final println statement (indicated below) is unconditional. So after incrementing i to 3, you still run that statement. The while condition only takes effect afterward, which is why it then stops after printing that.

    public class JavaApplication8 {
    
        public static void main(String[] args) {
    
            int i = 1;
            int j = 1;
    
            while (i <= 2 && j <= 4) {
    
                while (i <= 2 && j <= 4) {
    
                    System.out.printf("%d%d\n", i, j);
    
                    j++;
                }
    
                j = j - 4;
    
                i++;
    
                System.out.printf("%d%d\n", i, j); // <=== This one
                j++;
    
            }
    
        }
    }
    

    That whole thing can be dramatically simpler, though:

    public class JavaApplication8 {
        public static void main(String[] args) {
            for (int i = 1; i <= 2; ++i) {
                for (int j = 1; j <= 4; ++j) {
                    System.out.printf("%d%d\n", i, j);
                }
            }
        }
    }
    

    Live Example