[Solved] I need explanation why the output is a-b c-d [closed]


look at the snippet closely

    int x = 3;  
    while(x > 0) {      
        if(x > 2) {
            System.out.print("a"); 
        }

        x = x - 1;
        System.out.print("-");

        if(x == 2) {
            System.out.print("b c");
        }

        if(x == 1) {
            System.out.print("d");
            x = x - 1;
        }           
    }

when loop runs for the first time the value of x is 3 and the following operations happens

    while(x > 0) {      
        if(x > 2) {
            System.out.print("a"); // as the value is 3 so it ll print
        }

        x = x - 1; // here value is 2 now
        System.out.print("-"); // it ll be printed all the time the loop runs

        if(x == 2) {
            System.out.print("b c"); // again this ll be printed because the value is 2
        }

        if(x == 1) {
            System.out.print("d");
            x = x - 1;
        }           
    }

now the value of x is 2 and the following operations happen

    while(x > 0) {   // value of x is 2   
        if(x > 2) {
            System.out.print("a"); // it is skipped as the value of x is 2
        }

        x = x - 1; // now the value of x is 1
        System.out.print("-"); // it gets printed again

        if(x == 2) {
            System.out.print("b c"); // it gets skipped as the value is 1
        }

        if(x == 1) {
            System.out.print("d"); // it gets printed 
            x = x - 1; // loop gets over here as the value becomes 0
        }           
    }

i have simplified it so that you understand well 🙂

0

solved I need explanation why the output is a-b c-d [closed]