-1

I am studying how to program and have recently been working on a problem that calculates the total of 2 entered numbers from min to max. For example, if someone entered the numbers 4, 7. The calculation would be 4+5+6+7=22.

I've attempted what i think would be the definition of recSum but obviously it is wrong as I get a segmentation fault. What is wrong with my definition?

/* Define the recursive function */
int recSum (int x, int max)
{
int incrementalSum = 0;
if (x == max) 
{
   return x; /* Exit if summated lower to upper numbers */
}
else
{
   return (x + recSum(x++, max)); /* My recursive call */
}
} /* End of function call */

*new code is shown above, sorry, i used the wrong code.

C. Ben
  • 61
  • 9

3 Answers3

5

Your code has 3 important problems

  1. The expression

    incrementalSum = x + x++;
    

    is undefined, read this for more information

  2. Your function is not recursive, a recursive function calls it self until a condition happens where it should end.

  3. Also, noting that I am not an irrational "don't ever use goto person", this is precisely why some people advice against using goto.

Community
  • 1
  • 1
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
2

The reason your code doesn't work is this line:

return x + recSum(x++, max);

x++ increments x but returns the previous value, so in the recursive calls it never increments and you never reach the base case. Like an infinite loop. You have to replace x++ with ++x in order to give any result, even though it won't be correct. ++x is modifying x so it will alter the final sum of x + recSum. You'd better use:

return x + recSum(x + 1, max);

See What is the difference between ++i and i++?

Community
  • 1
  • 1
germanfr
  • 547
  • 5
  • 19
1

It seems you mean the following

int recSum(int x, int max)
{
    return max < x ? 0 : x + recSum( x + 1, max );
}

Or it would be even better to declare the return type of the function like long long int.

long long int recSum(int x, int max)
{
    return max < x ? 0 : x + recSum( x + 1, max );
}

The function can be called like

printf( "%lld\n", recSum( 4, 7 ) );

As for your function then it exits in the first call

int recSum(int x, int max)
{
    int incrementalSum = 0;
    recCall: if (x < max)
    return incrementalSum;
    ^^^^^^^^^^^^^^^^^^^^^

because usually it is called when x is less than max. So the function does not make sense. Moreover the function is not recursive because it does not call itself.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Excelent observation, this completes my answer. I think SO should have a method to allow answers to be merged and share the upvotes and downvotes among users. – Iharob Al Asimi Mar 04 '17 at 11:50