Adding several numbers without a loop

Is there a shorter way I can add 6 numbers without using a loop?

Here is my code:

sum = 1 + 2 + 3 + 4 + 5 + 6;


Yes, this is homework, but it is acceptable to submit the assignment the long way. I just want to reduce 6 variable declarations to 1, if possible (without using a loop). The textbook doesn't show a way, so either I overlooked it or it's not possible. . .
not sure if that's what you need but:
1
2
3
4
5
6
int x,sum;
while(x!=0)
{
	cin >> x;
	sum += x;
}
I don't think @super n00b wants a loop. If know you have 6 numbers, you can just use an array:
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

int main() {
    int vals[6] = {0};
    for (int i = 0; i < 6; ++i)
        std::cin >> vals[i];

    // adding
    int sum = vals[0] + vals[1] + vals[2] + vals[3] + vals[4] + vals[5] + vals[6];
    std::cout << "Sum: " << sum << std::endl;
    return 0;
}


Of course, really a loop should be used, but considering this is an assignment, whatever. Just never do it again.
Last edited on
That's what we call a loop, Edward01.

You could do so using recursion, if each number in the sequence can be derived from the last:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

int sumtorial( int value )
{
    if ( value )
    {
    	std::cout << value ;
    	
    	if (value - 1)
    		std::cout << " + " ;
    		
        value += sumtorial(value-1) ;
    }
    
    return value ;
}

int main()
{
    int result = sumtorial(6) ;
    std::cout << " = " << result << '\n' ;
}


http://ideone.com/o5nBni
If you have the numbers in an array or a std::vector or something, you could use std::accumulate:
1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <numeric>
#include <iterator>

int main()
{
    int array[6] = {1,2,3,4,5,6};
    std::cout << "Sum: ";
    std::cout << std::accumulate(std::begin(array), std::end(array), 0);
}
Sum: 21
^^^

That's just abstracting from the loop. lol
Topic archived. No new replies allowed.