waifu_nom
waifu_nom

Reputation: 33

Nested for loop output not correct

 for(int c = 1; c <= rows; c++) {
      for(int i = 0; i < c; i++) {
          System.out.print(++number + " ");
      }
 }

let us assume that rows = 5 and number = 0 initially. what will be the output?

to me, if rows were 5, the output would be as follows: 1 2 3 4 5

however my teacher has it as: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

and i can't seem to wrap my head around it! can anyone explain why ? i have tried with different numbers as well, for 2, i would get just the number 1,2 but my professor gets 1,2,3

Upvotes: 3

Views: 74

Answers (3)

Eklavya
Eklavya

Reputation: 18420

For every row with the inner loop execute System.out.print(++number + " "); this statement total 15(1 + 2 + 3 + 4 + 5) times and every time number value is implemented and print.

Take a look visualization here

Upvotes: 1

chirag sharma
chirag sharma

Reputation: 24

The best way to understand this type of problems is dry-run. I am sharing a two step dry-run hoping that will be helpful: dry-run

Upvotes: -2

Eran
Eran

Reputation: 393781

You have two nested loops.

The outer loop iterates from 1 to 5.

The inner loop iterates from 0 to c - 1.

When c == 1, the inner loop iterates from 0 to 0 so number is incremented 1 time.

When c == 2, the inner loop iterates from 0 to 1 so number is incremented 2 times.

When c == 3, the inner loop iterates from 0 to 2 so number is incremented 3 times.

When c == 4, the inner loop iterates from 0 to 3 so number is incremented 4 times.

When c == 5, the inner loop iterates from 0 to 4 so number is incremented 5 times.

In total, number is incremented 1 + 2 + 3 + 4 + 5 == 15 times.

Each time number is incremented, it is also printed, followed by a space. So the loops produce the output 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15.

Upvotes: 2

Related Questions