while statements

Jun 8, 2013 at 9:08pm
I'm supposed to write a program that uses a while to sum the numbers from 50 to 100.

Based on the example from the C++ primer book, I replaced some numbers with 50 to 100, but I got a high number. This is my code
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
int main()
{
    int sum =0, val = 50;
    while (val<=100) {
        sum += val;
        ++val;
    }
    std::cout << "Sum of 50 to 100 inclusive is " << sum << std::endl;
    return 0;
}


hmm apparently the answer is 3825, but when I random numbers like 50 100 and 0, there are other ways to get 3825. Does anyone have an explanation?
Last edited on Jun 8, 2013 at 9:36pm
Jun 8, 2013 at 10:00pm
I don't understand what you are asking. Also, what do you mean by random numbers?

The correct answer is 3825.

You can calculate the sum of the integers from 1 to n using the formula
n * (n+1) / 2
sum of 1 to 100 = 5050
sum of 1 to 49 = 1225

sum of 50 to 100 = 5050 - 1225 = 3825

Last edited on Jun 8, 2013 at 10:00pm
Jun 8, 2013 at 10:02pm
For int sum= ____, I can put 0, 50,100 and it'll give me 3825 sometimes.
Same with val =
and
while (val<= )
It's like there are other ways for me to get it correct.
Jun 8, 2013 at 10:10pm
Sorry, I must be very slow today (there are distractions around me).

Your original code appears correct to me. Can you post an example of one of the other ways that you used.
Jun 8, 2013 at 10:34pm
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
int main()
{
    int sum =50, val = 50;
    while (val<=100) {
        sum += val;
        ++val;
    }
    std::cout << "Sum of 50 to 100 inclusive is " << sum << std::endl;
    return 0;
}


seems to work as well.
Jun 8, 2013 at 10:48pm
The second version posted results in 3875 when I run it. The original program gave 3825.
Perhaps a 2 and a 7 might look visually similar and gave the illusion that the answers were the same?

Jun 8, 2013 at 10:53pm
Would you happen to know the difference between the first and the second program since they give different answers. I'm assuming the int sum added the 50 to it and you're supposed to keep it at 0 all the time unless told otherwise correct?
Jun 8, 2013 at 11:07pm
The method used in the first program was correct. That is the initial value of sum should be zero. That's a general principle when accumulating the total, start with a total of 0 and for each item processed, add the value to the total (or sum).

Since the second program starts with sum = 50 it will give the wrong answer, unless you skip the first value of val, like this:
1
2
3
4
5
    int sum =50, val = 51;
    while (val<=100) {
        sum += val;
        ++val;
    }

But although that now gives the correct answer, the code is confusing, more difficult to understand and more difficult to maintain. Something to be avoided.
Jun 8, 2013 at 11:10pm
Oh okay, I get it now. Thanks!
Topic archived. No new replies allowed.