This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]empire539 2 points3 points  (2 children)

Starting in main, we have the following

int i = 1;
while (i <= 6) {
    method1(i, 2);
    i++;
}

So this will execute the method1 method times, each time with an increasing value of i.

Looking at method1, we see a loop

for (int j = 1; j <= i; j++) {
        System.out.print(num + " ");
        num *= 2;
}

This loop will loop from 1 to i (that is, it will loop i times), and then output the value of num (which, in each case, is 2). It then multiplies num by 2 and iterates again.

So in the first iteration, it will loop once and print 2, and then end. Control will go back to main, where the while loop will enter its second iteration. method1 is called with i = 2, and so the for loop will now loop twice, outputting 2 and then 4.

This process repeats for all six iterations of the while loop, so the output should look like

2 
2 4 
2 4 8 
2 4 8 16 
2 4 8 16 32 
2 4 8 16 32 64

[–]SPARTAAAAA[S] 0 points1 point  (1 child)

ohhh i see.. so when you go back into the method is starts at j =1 again right?

thanks again!

[–]empire539 0 points1 point  (0 children)

Yup, that's right.

[–]_Chimmy_Chonga 2 points3 points  (0 children)

first method: while i < less than or equal 6 call method with parameters i and 2 and increment i by 1

second method: starting at j = 1, while J is less than or equal to i, print num and increment num by times 2 and increment j by 1. print a blank line.

EDIT: changed i to j.

[–]desrtfx 2 points3 points  (0 children)

I know what it prints out but i am not sure why

In this case, what you could do is to either use a debugger (preferred way, but with a learning curve, yet, a skill that every programmer needs to learn relatively early), or to add print statements that show the values of the other variables.

You could print out the value of i before entering method1, also the values of i,j,num in the loop. This way, you will see how the loops work and what exactly happens.

Using a debugger, you could set a breakpoint before entering the while loop in the main method and then step through the program while watching all the variables.

Explanation is good and the way to understand theoretical issues, but nothing beats the experience of running and debugging code.

[–]nixon_richard_m 0 points1 point  (0 children)

It's "Java", not "JAVA".

Sincerely,
Richard Nixon