I'm in AP Computer Science A* I was doing the following problem:

int i = 1; 
    while ( i < 10 ) 
    { 
      int j = 10; 
      while ( j > i ) 
        j--; 

      i += j; 
    }
System.out.print(i);

The output is 16, but can someone please explain why it is 16? I tried solving it by paper and kept on getting 10. If anyone could please tell me exactly why that'd be great. Thanks :)

To tell you where you went wrong, it'd be good to know how you got to ten. For each iteration of the outer while loop what's the value of i going in, what's the value of j after the inner while loop and what's the value of i after incrementing it by j?

To see what is going on, before line 8, put in a printf statement that will output i and j. That may help you see the behavior of the algorithm. IE:

    int i = 1;
    while ( i < 10 )
    {
        int j = 10;
        while ( j > i )
        {
            j--;
        }
        System.out.printf("i == %d, j == %d\n", i, j); 
        i += j;
    }
    System.out.print(i);
commented: Exactly! That's how to understand it. +15
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.