Calculation that adds in order from 1

I would like to calculate by adding 1 to 10 in order.

sum = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10

You can still output it, but it's not cool, so I'd like to create a program using the times statement.

Prepare a variable sum to store the total value.

sum = 0

Add 1 to 10 to the variable sum in order.

sum = 0

sum = sum + 1
sum = sum + 2
sum = sum + 3
sum = sum + 4
sum = sum + 5
sum = sum + 6
sum = sum + 7
sum = sum + 8
sum = sum + 9
sum = sum + 10

Alternatively, use the self-assignment operator

sum = 0

sum += 1
sum += 2
sum += 3
sum += 4
sum += 5
sum += 6
sum += 7
sum += 8
sum += 9
sum += 10

You can shorten the description by doing.

Furthermore, the times statement is used to summarize the repeated processing.

sum = 0
10.times do |i|
  sum += i + 1
end

puts sum

In the times statement, the number of repetitions is automatically assigned as a numerical value in the variable i, so i can be used to add the number of repetitions to the variable sum. Since the first i is 0, set it to i + 1.

Recommended Posts

Calculation that adds in order from 1
Extract elements in order from a class type ArrayList
Birthday attack calculation in Ruby
The story that Tomcat suffered from a timeout error in Eclipse