Search code examples
javafor-loopnested-loops

Nested loop Confusion


public class Exon303 {
    public static void main(String[] args) {
        int k = 109;

        do {
            for(int i = 3; i < 9; i = i * 2) {
                if(k % i ==3) {
                    k = k / 3;
                } else {
                    k = k / 2;
                }
            }
            System.out.println(k);
        } while(k > 0);
        for(int i = 0; i < 2; i++) {
            for(int j = 0; j < 2; j++) {
                for(int m = 0; m < i * 2; m++) {
                    if(m == j && m == i) {
                        System.out.println("i: " + i);
                        System.out.println("j: " + j);
                        System.out.println("m: " + m);
                    }
                }
            }
        }    
    } 
}

Can someone explain to me the output of these loops I created I've hand traced it twice now and for some reason, I am getting a different output when I trace it.

Expected output:
27
6
1
0
i: 1
j: 1
m: 1

Here is my handtraced output below

Handtraced output:
54 
27
9
4
2
0
i: 0
j: 0
m: 0
i: 1 
j: 1
m: 1

Solution

  • You was wrong in tracing your code by hand. Let me explain.

    Separate your code to 2 parts. 1st part:

        int k = 109;
    
        do {
            for(int i = 3; i < 9; i = i * 2) {
                if(k % i ==3) {
                    k = k / 3;
                } else {
                    k = k / 2;
                }
            }
            System.out.println(k);
        } while(k > 0);
    

    You printed k outside of for loop, then k / 2 twice each for loop (i = 3, 6), after 1st while loop, k = (k / 2) / 2 = 27. It is the same with next while loops when k does not have any value that make k % i == 3. So next values of k in each while loop is 27/4 = 6 and 6/4 = 1. This is k, i values at beginning of each for loop:

    ---- while loop ----
    k = 109, i = 3
    k = 54, i = 6 => print k / 2 = 27
    ---- while loop ----
    k = 27, i = 3 
    k = 13, i = 6 => print k / 2 = 6
    ---- while loop ----
    k = 6, i = 3 
    k = 3, i = 6 => print k / 2 = 1
    ---- while loop ----
    k = 1, i = 3 
    k = 0, i = 6 => print k / 2 = 0
    ----> k == 0, break while loop
    

    2nd part:

        for(int i = 0; i < 2; i++) {
            for(int j = 0; j < 2; j++) {
                for(int m = 0; m < i * 2; m++) {
                    if(m == j && m == i) {
                        System.out.println("i: " + i);
                        System.out.println("j: " + j);
                        System.out.println("m: " + m);
                    }
                }
            }
        }    
    

    The condition to print i, j, m values is m == j == i and i, j only have 2 values 0, 1, but the condition m < i*2 make for loop of m is ignored when i = 0 and m = 0. So the only output: i = j = m = 1.