'Write a program that adds together all the integers from `1` to `250` (inclusive) and `puts`es the total

How would I do this using ruby and only using a while loop with if, elsif and else only?



Solution 1:[1]

You don’t need a while loop to implement this. But if they want a while loop…

n = 250
while true
    puts ( n * (n + 1)) / 2
    break
end

    

Some of the comments have alternatives that are interesting, but keeping this one because it has the flow of control at least pass through the while loop. Not sure if it counts as using a loop if control doesn't even enter the body of the loop.

Solution 2:[2]

sum = 0
i = 1

while i < 251
   sum += i
   i += 1
end

puts sum

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2