Module: For loop statement. Typical tasks


Problem

1/16

Sum of Sequence Numbers - Example 1

Theory Click to read/hide

Let's try to write a program to solve the following problem:
Find the sum of all integers between 100 and 500. 

When solving this problem, it becomes difficult to find the sum. If we simply write the result of the addition to the variable s, for example, as


s=100+101+102+103+...+500

it will take a lot of time for the recording itself, because the computer will not understand how to use the ellipsis in the arithmetic expression and we will have to write all the numbers from 100 to 500 into this sum. And the value of such a program would be negligible. Especially if we want to change our numbers and take a different range.

What should we do?

If we pay attention to the entry above, then we constantly use the addition "+".
You can try to add numbers to the variable s gradually. For example, using this notation
s := s + i;
what we did here:
1) on the right we put the expression s+i, , that is, we take the value of the variable s, which we now have in memory and add the value of the variable i< to it /strong>
2) on the left we set the name of the variable s, that is, the entire result of the calculation on the right will be stored in this variable, so we will change the value of the variable s. 

Where can we get numbers from our range?

Numbers from 100 to 500 that belong to our range should fall into the i variable one by one. And this can be done using the well-known for
loop For example, in this way
s := 0; //at the beginning it is necessary to reset the variable s, so that at the first step the number 100 is added to zero, and not to what is in memory!
for i := 100 to 500 do //header of the loop, in which the variable i changes its value from 100 to 500 in increments of 1
    s := s + i; //the body of the loop, in which we gradually add the value of the changing variable i to the variable s
                 // and the result is stored back in the variable s
This solution is very similar to calculating the sum by actions
 s = 0 + 100 = 100
 s = 100 + 101 = 201
 s = 201 + 102  = 303
etc.

Problem

1. Run the program analyzed in the theoretical part for execution, see the result of its work