loop for sum...

How to write a for loop which sums all values between 10 and 100 into a variable called total? Assume that total has NOT been initialized to zero.
Well, I think there is sth in your problem I don't get.

Assume that total has NOT been initialized to zero.

You mean you can't initialize it to zero? because if it is not initialized to zero at first, you can simply set it to zero before you start your loop and write it! If you have problem with writing loops, see
http://www.cplusplus.com/doc/tutorial/control.html
Last edited on
A perfect example for template metaprogramming :)

1
2
3
4
5
6
7
8
9
10
#include <iostream>

template< int N >
struct Sum {
   enum { value = N * ( N + 1 ) / 2 };
};

int main() {
   std::cout << Sum<100>::value - Sum<10>::value << std::endl;
}

Perhaps it would be a perfect example if it would fulfill the requirements defined above:
How to write a for loop [...]


Though the questions remain: (a) why a loop? and (b) what do you mean by "not initialized to zero"? That the value should be added, or that you have to initialize to zero first, or that you are not allowed to initialize, ...?
why not initialize total with 10?:P... he wants a loop like this, i guess:

1
2
3
4
for(int i=11;i<100;i++)
{
total= (total + i);
};
Last edited on
Given a list of numbers (any list will do, so my example will be short)

4 5 6 7 8 9

And the requirement to sum those numbers without initializing the sum variable (total) to zero, consider how you would sum the numbers in your own head, or on paper during a 4th grade math test.

4 + 5 = n1
n1 + 6 = n2
.
.
.
n4 + 9 = ntotal

What is n0 ?

Hope this helps.

[edit] Fixed the list of numbers to be easier to digest
Last edited on
Topic archived. No new replies allowed.