Program Writing

Write a program that uses a function to calculate the sum of all numbers from 1 to n then prints the result to the screen. The name of the function should be: sum. e.g. if n=5 then sum= 1+2+3+4+5
Is that so hard? Did you even TRY? Probably not, as you copied this topic in the "Beginners" section.
Hey, now, EssGeEich, maybe someone is just having a few problems with loops.

@tate1: We won't write the program for you, though. You will have to both look up "for loops" and solve the problem on your own. Sorry. :)

-Albatross
1
2
3
4
5
6
7
8
9
10
11
#include <type_traits>
#include <iostream>

template< typename INT_TYPE > inline
typename std::enable_if< std::is_integral<INT_TYPE>::value, INT_TYPE >::type
sum( INT_TYPE n ) { return n * (n+1) / 2 ; }

int main()
{
    std::cout << sum(5) << '\n' ;
}

i am new to the course and really need help
@JLBORGES...thanks for the help..i am tryin to understand it now
I wouldn't really bother looking at JLBorges's example. He posted something that he probably knew would be way out of your current level of skill. Pretty much everyone who knows the language considers templates to be advanced C++. >:/

Instead, if you feel you are either weak on functions or loops, try reading through these.
http://cplusplus.com/doc/tutorial/control/#for
http://cplusplus.com/doc/tutorial/functions/

That should give you the knowledge you need to solve the problem, assuming you already know about variables. :)

-Albatross
Sorry, Albatross, but i didn't even read anything from it, not even a line of code, so I tought it was the random student (Well, it actually IS a student) and just tought: "You should have listened to your teacher"...
> .i am tryin to understand it now

To add up all numbers from 1 to n, you could do something like this:

1
2
3
int result = 0 ;
for( int i=1 ; i<=n ; ++i ) // iterate from 1 to n
    result += i ; // adding each number to the result   


However, 1 + 2 + 3 + .... + n is the sum of an arithmetic progression;
this is equal to n * (n+1) / 2
See http://en.wikipedia.org/wiki/Arithmetic_progression


Although true, I still wonder if the purpose of the exercise wasn't to verify that the student knows about looping and functions.

-Albatross
Topic archived. No new replies allowed.