[Ruby] [ruby] Drill output

2 minute read

Content

image.png

Implementation

image.png

Comment

This time, I created a program that adds numbers 1 to 10 in order. Below is the code I tried first. image.png The following is the output. image.png This program is 1+2+3+4+5… so it’s a failure.

Then what should I do (-_-;) Let’s explain one by one

① Prepare a variable sum to store the total value ② Add numbers 1 to 10 to the variable sum in order ③ Replace the process of adding in order by repeating the times statement ④ Output the value of the variable sum to the terminal

First is ①. Add 1 to 2, Add 3 to the result, Add 4 to the result, Add 5 to the result and repeat until … and 10.

So we need a variable that will always store the result. Define this as the variable name sum. Since we have not added anything yet, substitute 0 for sum.

② Add numbers 1 to 10 to the variable sum in order Let’s write a program that adds numbers 1 to 10 to the variable sum in order. image.png Since this code is very long and the same process continues, we will rewrite it with a times statement to make it more efficient.

③ Replace the process of adding in order by repeating the times statement You can use the times statement to put together the same operations that are repeated many times. This time, the sum += number part is summarized.

The times statement describes the number of times you want to repeat.times and decide the number of times to repeat. This time, since 1 to 10 are added in order, similar processing is repeated 10 times. Therefore, you want to repeat 10 times. image.png What should I do about the numerical part? This number changes with each iteration. The first is 1, the second is 2, and the third is 3. That is, the same as the number of repetitions. In the times statement, the number of iterations is automatically assigned to the variable i as a numerical value. Therefore, if you use the variable i, you can add the number of iterations to the variable sum. However, since it is a program, the value of i for the first time is 0. Therefore, add 1 to i and add 1 to sum. image.png ④ Output the value of the variable sum to the terminal Finally, output sum with the puts method to the terminal, and you’re done.

Tags:

Updated: