RECURSION

im trying to sum integers, but i dont knw where the flaw is in this code
just tell me where is the flaw in this code, dont give other ways to solve this question

#output should be 6
# but code gives 4

#include <iostream>
using namespace std;

int SUM(int n) {
cout<<n<<endl;

if(n!=1)
return n + SUM(--n);

return n ;
}
int main() {

cout<<SUM(3)<<endl;

}
> return n + SUM(--n);

This engenders undefined behaviour.

If a side effect on a scalar object is unsequenced relative to a value computation using the value of the same scalar object, the behavior is undefined. http://en.cppreference.com/w/cpp/language/eval_order

Instead, write: return n + SUM( n-1 ) ;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

int sum( int n )
{
    if( n < 0 ) return -sum(-n) ; // negative number
    
    if( n == 1 ) return n ;
    
    return n + sum( n-1 ) ; // *****
}

int main()
{
    std::cout << sum(3) << '\n' // 6
              << sum(-4) << '\n' ; // -10
}

http://coliru.stacked-crooked.com/a/f0178a7515ad33b7
Because of the nature of recursion in that it calls itself infinitely unless an exit statement is reached, any type of recursion needs an exit statement (unless you're researching stuff and specifically want to crash something)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int SUM(int n) { 
cout<<n<<endl; 

if(n==0)
    return n;
else
    return n += SUM(n-1); 

return n ; 
}
int main() { 

cout<<SUM(3)<<endl;

}


I gave your code an exit statement and fixed up some syntax
Yfhng, youre wrong there, code is not going infinity , it has a proper base case
Can someone please explain me what is un sequenced ? and sequenced
closed account (48T7M4Gy)
Click on the reference at the end of JLBorges' sentence above.
Topic archived. No new replies allowed.