Module: For loop statement. Typical tasks


Problem

1/16

The sum of the sequence numbers is 1

Theory Click to read/hide

Task
Find the sum of all integers between 100 and 500. 

Let's write a program that solves this problem without using a formula. If we just write the result of the addition to the variable s, for example, as
\(s=100+101+102+103+...+500\),

we will spend a lot of time on the recording itself, because the computer will not understand how to use the ellipsis in an arithmetic expression and we will have to write all the numbers from 100 to 500. And the value of such a program will 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 adding numbers to the s variable gradually. For example, using this notation
s = s + i.
What we did:
1) on the right we put the expression s + i, , that is, we take the value of the variable s and add the value of the variable to it i;
2) on the left we set the name of the variable s, that is, the entire calculation result on the right will be stored in the same variable s, so we will change the value of the variable s
It remains only to change the value of the variable i in the desired range. This can be done with a for.
loop  
The numbers from 100 to 500 that are in our range should go into the i variable in turn. 
Example
// IMPORTANT! First you need to reset the variable s, // so that at the first step the number 100 is added to zero, // and not to what's in memory! s=0; for ( i = 100; i <= 500; i++) // loop header in which the variable i s = s + i; // changes its value from 100 to 500 in increments of 1, // in the body of the loop gradually to the variable s,   // add the value of the changing variable i, // and the result is stored back in the variable s This solution is very similar to calculating the sum over actions:
\(s = 0 + 100 = 100, \\ s = 100 + 101 = 201, \\ s = 201 + 102 = 303 \\ ... \)

Problem

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