Can´t the faulty logic in this code

Hello there.

I´m trying to perform a sum from 50 to 100 using while.

With the following code I´m getting the result 3825, but it is supposed to be 3750.

Where is the mistake?

1
2
3
4
5
6
7
8
9
10
11

#include <iostream>
int main()
{
int soma = 0, variavel = 50;
while (variavel <=100)
	{soma += variavel;
	++variavel;}
std::cout  << "The sum of 50 to 100 inclusive is " << soma <<std::endl;
return 0;
}
Last edited on
The result is in fact supposed to be 3825.
Sum 1 to 49 = 1225
Sum 1 to 100 = 5050
difference = 5050 - 1225 = 3825

Note: Formula for sum of series 1 + 2 + 3 + .... + n
= n * (n + 1) / 2

edit: previously I misstated the formula
Last edited on
Oh yes, the 3750 value I got from faulty logic. It is supposed to be 50 (first number of the series) plus 100 (last number) times the number this sum repeats, all divided by two. The 150 value is repeated 51times and not 50 like I first thought.

Thanks for your input.
Topic archived. No new replies allowed.