Search code examples
javaif-statementwhile-loopbreak

While loop with true, if and break


How do i change these two While loops into other two while loops (the output should be the same) using "while (true) { ... })" and using "if" and "break" inside the loop to terminate it?

The output

0 1 2 3 4 5 6 7 
42 36 30 24 18 12 6 
int m = 0;

while (m <= 7) {
    System.out.print(m + " ");
    m++;
}

System.out.println();
int MM = 42;
while (MM >= 6) {
    System.out.print(MM + " ");
    MM -= 6;
}

System.out.println();

Solution

  • int m = 0;
    
    while (true){
        System.out.print(m + " ");
        m++;
        if(m > 7){
            break;
        }
    }
    
    System.out.println();
    int MM = 42;
    while (true) {
        System.out.print(MM + " ");
        MM -= 6;
        if(MM < 6){
            break;
        }
    }
    
    System.out.println();