Sum of numbers

The next task we were asked to perform was a program capable of adding the numbers inside a user specified range. The user provides the first value of the range and the last value of the range. We were asked to preferably use loops to solve this task.

This program was a bigger challenge for me. It helped me to really understand the way a counter works. It is kind of strange and hard to undestand how a variable is initializaed under the value of another one, and then inside the loop you initialize it to the value of itself plus one.

First I thought I had to use a for loop to run this program. But it was getting to hard for me and I could not do it. My fellow classmate and friend Alberto Rodriguez gave me a general idea of how it should work, using a do while loop.

So how this basically works is that the sum varable is initialized to the value of the first number of the range, before the for loop starts working. Inside the for loop, you intialize the sum funtcion again to the value of itself (which is now the value of the first number of the range) plus one. Then you make the actual operation, which is to add the value of the first number of the range plus the variable sum.

The program will keep on doing the operation while the value of sum is less than the last value of the range.

#include <iostream>

using namespace std;

int x, y, sum;

int main (){

cout << “Provide the first number of the range: ” << endl;
cin >> x;

cout << “Provide the last number of the range: ” << endl;
cin >> y;

sum = x;

do{

= sum + 1;
x = x + sum;
}
while (sum < y);
cout << “The answer is equal to: ” << x;
}

CC BY-SA 4.0 Sum of numbers by netosanchezb is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.