Module: (C++) For loop operator. 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 from 100 to 500.

When solving this problem, difficulty arises in finding the amount. If we just write the result of the addition into 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 arithmetic terms and we will have to write all the numbers from 100 to 500 in this amount. And the value of such a program will be insignificant. Especially if we want to change our numbers and take a different range.

What do we do?

If we pay attention to the record above, then we constantly use the addition of "+".
You can try adding numbers to the variable s gradually. For example, using such a record
s=s+i;
what we did here:
1) on the right, we set the calculation of 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
2) on the left we put 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 change the value of the variable s.

Where to get numbers from our range?

The numbers from 100 to 500, which belong to our range, must alternately fall into the variable i. And this can be done using the for loop known to us.
For example, in this way
s=0;          //at the beginning it is necessary to reset the variable s, so that in the first step the number 100 is added to zero, and not to what is in memory!
for ( i = 100; i<=500; i++)  //the header of the loop in which the variable i changes its value from 100 to 500 in steps of 1
    s = s + i;   // body of the loop, in which we gradually add the value of the variable i to the variable s
                  // and save the result back to the variable s
This solution is very similar to calculating the amount in steps
 s = 0 + 100 = 100
 s = 100 + 101 = 201
 s = 201 + 102  = 303
и т.д.

Problem

1. Run the program disassembled in the theoretical part, see the result of its work