3 Replies - 447 Views - Last Post: 19 March 2019 - 06:05 AM Rate Topic: -----

#1 skromanflow   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 18-March 19

Nested for loop question

Posted 18 March 2019 - 01:05 AM

Hello,

I need to understand this two pieces of code:
int t = 0;
		
for (int i = 1; i <= 2; i++) {
    for (int j = 1; j <= i; j++) {
        t = t + j;
   }
}
System.out.println(t); // for t + j is 4 but for t + i = 5 I am not sure how?


I stucked for few hours on this, and I would be grateful If someone could explain it to me
Thanks!
Is This A Good Question/Topic? 0
  • +

Replies To: Nested for loop question

#2 andrewsw   User is offline

  • never lube your breaks
  • member icon

Reputation: 6813
  • View blog
  • Posts: 28,184
  • Joined: 12-December 12

Re: Nested for loop question

Posted 18 March 2019 - 01:42 AM

Have you traced through what happens to the values with paper and pencil?

Or run the code and print out the values of i, j and t at each iteration.
Was This Post Helpful? 0
  • +
  • -

#3 macosxnerd101   User is offline

  • Games, Graphs, and Auctions
  • member icon




Reputation: 12641
  • View blog
  • Posts: 45,813
  • Joined: 27-December 08

Re: Nested for loop question

Posted 18 March 2019 - 08:08 PM

Moved to Java.

Stick the println statement inside the inner loop to see the values that are being printed out at each iteration.
Was This Post Helpful? 0
  • +
  • -

#4 astonecipher   User is offline

  • Senior Systems Engineer
  • member icon

Reputation: 2915
  • View blog
  • Posts: 11,331
  • Joined: 03-December 12

Re: Nested for loop question

Posted 19 March 2019 - 06:05 AM

printing the variables out will help you understand,

At the basic level it is an iteration of iterations.

for(/.../)
    // for every loop the out side does
    for(/.../)
    // this loop will iterate x times


So,
int t = 0;
		
for (int i = 1; i <= 2; i++) { <--- will loop twice
    for (int j = 1; j <= i; j++) { <--- will loop however many times it is designed to * the number of out iterations
        t = t + j;
   }
}

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1