May 15, 2012 at 8:19pm UTC
Question: Write a function named SumTo() that takes an integer parameter named nValue, and returns the sum of all the numbers from 1 to nValue.
I am not getting the correct output. Is there anything wrong in the logic? Please help
#include<iostream>
using namespace std;
int SumTo(int nvalue)
{
for(int iii=0; iii < nvalue; iii++)
{
nvalue= nvalue+iii;
}
return nvalue;
}
int main()
{
int nvalue;
cout << "Enter a number= ";
cin >> nvalue;
int sum;
sum= SumTo(nvalue);
cout << "the result is " << sum;
return 0;
}
May 15, 2012 at 8:30pm UTC
1 2 3 4 5 6 7 8 9 10 11
int SumTo( int nvalue )
{
int sum = 0;
for ( int i = 1; i <= nvalue; i++ )
{
sum += i;
}
return ( sum );
}
In fact the sum is equal to nvalue*(nvvalue + 1)/2
So the function could be written as
inline int SumTo( int nvalue ) { return ( nvalue * ( nvalue + 1 ) / 2 ); }
Last edited on May 15, 2012 at 9:24pm UTC
May 15, 2012 at 8:47pm UTC
Thanks for the reply. I am aware about the sum of n numbers but, I had to use the 'For' loop specifically for this question.
Also, can you please tell me what was wrong in my logic. I am getting te result if I do it in paper but the console output is giving me -2147450875 !!! (say for first 5 numbers). What am I missing here?
May 15, 2012 at 8:49pm UTC
You always increse nvalue. So iii will be always less than nvalue until nvalue will not become negative.
1 2 3 4 5
for (int iii=0; iii < nvalue; iii++)
{
nvalue= nvalue+iii;
}
Last edited on May 15, 2012 at 9:23pm UTC
May 15, 2012 at 8:53pm UTC
Oh yeah. Absolutely Right. Got your point. Thanks :)