Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Ben Dowsett
Ben Dowsett
6,780 Points

While loop counting confusion

HI Can somebody please describe what y is doing in this Ruby while loop - I understand that n is iterating each by 1 each time but I can't get my head around what y is doing.

```n = 0 y = 0

while n < 251 y = n + y n = n + 1 end

puts y```

2 Answers

n = 0
y = 0

while n < 251 
  y = n + y 
  n = n + 1 
end

puts y

The line y = n + y adds the values of n and y together and stores the result as y.

In the first run of the while loop, n and y are both 0, so y = n + y is y = 0 + 0, which sets y to 0. n is then increased.

In the second run of the while loop, n has been increased to 1 and y is 0, so y = n + y becomes y = 1 + 0, which sets y to 1. n is then increased.

In the third run of the while loop, n has increased to 2 and y is 1, so y = n + y is y = 2 + 1, which sets y to 3. n is then increased.

In the fourth run of the while loop, n is 3 and y is 3, so y = n + y is y = 3 + 3, which sets y to 6. n is then increased.

In the fifth run of the while loop, n is 4 and y is 6, so y = n + y is y = 4 + 6, which sets y to 10. n is then increased.

...

In the 251th run of the while loop, n is 250 and y is the value of 249 + 248 + ... + 1 + 0, so y = n + y is y = 250 + 249 + 248 + ... + 2 + 1 + 0. n is then increased.

In the 252nd run of the while loop, n is 251 and y is the value of 250 + 249 + ... + 1 + 0, and n is not less than 251, which ends the while loop.

The value for y is then printed, which is the sum of integers from 0 to 250, which is 31375 .

Ben Dowsett
Ben Dowsett
6,780 Points

Thank you, really helpful