-3
public class testing
{
    public void show() {
        int num = 0;
        int n = 5;
        for (int i=1; i<n; i++) {
            for (int j=0; j<i; j++) {
                System.out.print(num++);
                System.out.print(" ");
            }
            System.out.println(" ");
        }
    }
}

This question came up in one of our previous exams and I don't understand it. The answer is

0  
1 2  
3 4 5  
6 7 8 9 

But I have no clue how they got it. I kind of understand the 2nd to 4th line but have no clue how they got 0 on the first line. Any explanation would be highly appreciated, thanks!

Nino
  • 1
  • 1
    Do you know how to do a "desk check"? (ps - `num++` is a post increment) – MadProgrammer Apr 14 '15 at 05:57
  • Does desk check mean working it out on paper? If so, I have tried doing that, but am stuck at how they got 0 on the first line. I can't get '0'. Mine goes straight to '1'. Wait a minute, does that mean my code prints "num" and THEN increments it by 1? – Nino Apr 14 '15 at 05:58
  • [this](http://stackoverflow.com/q/2371118/2764279) will surely help you – earthmover Apr 14 '15 at 06:01
  • num starts as a 0, in the first iteration of both loops you print it. System.out.print(num++); means you first print the value of num and than increment it by 1 – svarog Apr 14 '15 at 06:17

2 Answers2

1

but have no clue how they got 0 on the first line ?

int num = 0; --> it is 0 initially

For the first iteration your inner loop executes only 1 time

for (int i=1; i<n; i++) {
   for (int j=0; j<i; j++) { ---> for(int j=0;j<1;j++) // for 1st time

So that is why the below line

System.out.print(num++); //printed 0

Note : there is a tool known as debugger , Use it !!

Neeraj Jain
  • 7,643
  • 6
  • 34
  • 62
0

Maybe the following amended code could help to understand

int num = 0;
int n = 5;
for (int i=1; i<n; i++) { // loop from 0 to 4
    System.out.printf("num=%d  i=%d  :  ", num, i);
    for (int j=0; j<i; j++) { // loop from 0 to i
        System.out.print(num++); // print num then increment num
        System.out.print(" ");
    }
    System.out.println(" ");
}

output

num=0  i=1  :  0  
num=1  i=2  :  1 2  
num=3  i=3  :  3 4 5  
num=6  i=4  :  6 7 8 9  

I believe your problem lies in this line

System.out.print(num++);

in a more verbose way it does the following

System.out.print(num);
num = num + 1;
SubOptimal
  • 22,518
  • 3
  • 53
  • 69