-3

I have found this code as an example but do not understand how it's executed, mainly for the System.out.println() line item.

for ( int i = 1; i <= 5; i++) {
    for ( int j = 1; j <= i; j++) {
      System.out.print( i );
    }
      System.out.println();
}

Result:

   1
   22
   333
   4444
   55555

How does it stack up the numbers?

Also, what is the difference between System.out.print( i ) and System.out.println( i )?

Any explanation would be appreciated, thanks!

akinom
  • 3
  • 1
  • Do some more study yourself and try to solve it your self, it is not that much hard – Grijesh Chauhan Feb 22 '15 at 12:40
  • The reason it stacks up the numbers is because when using `System.out.print(i)` it will continue printing on the same line, until you tell it to start printing on a new line by using `System.out.println()` or adding a `\n`. – James Feb 22 '15 at 12:40
  • Thanks James. So in terms of the execution, it will run the inner FOR loop till the condition holds and prints those numbers. Once it stops holding, it goes to the next step and moves to printing on the next line. Now it confirms the condition of the outer FOR loop, if it holds, goes to inner loop and so goes on. Do I have it right? – akinom Feb 22 '15 at 12:47

1 Answers1

0

How does it stack up the numbers?

It stacks by using println() which moves cursor to new line. So when your inner loop (with j variable) ends, outer loop hits the new line.

System.out.print( i ) and System.out.println( i )?

print - prints in the same line where cursor is. println - prints to the next line according to previous cursor position.

00Enthusiast
  • 103
  • 7
  • I think "println - prints to the next line according to previous cursor position." is not very correct -- I believe it print 'a line' were cursors was....it cursor was at (x,y) coordinates then it will print chars from (x,y) after writing string it also writes "\n" that causes any *next* print execution start with new line y+1 – Grijesh Chauhan Feb 22 '15 at 12:50