0

What does this code do? Why does it have two return values?

int MSum(int N){
   if (N == 1)
       return 1;
   return N + MSum(N - 1);
}

I tried writting the phollowing program to run it. It compiles fine, but I get error when I run it:

#include <stdio.h>
int MSum(int N);

int main(){
    int n, o;
    printf("Εισάγετε ακέραιο: ");
    scanf("%d", &n);
    o = MSum(n);
    printf("%d", o);
    return 0;
}

int MSum(int N){
    if (N == 1)
        return 1;
    return N + MSum(N - 1);
}

The error I get is:

/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/Scrt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
collect2: error: ld returned 1 exit status
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
adonle
  • 1
  • 3
    How are you compiling this code? – dbush Dec 28 '18 at 15:24
  • @dbush ditto. Show your compilation statement. – Sourav Ghosh Dec 28 '18 at 15:28
  • Your program compiles and executes correctly on my system. Have you touched the code before posting? It complains about a missing `main()` function, but you have one. Have you tried your posted code? I would have added a `\n` in the printf() call only, but it's perfectly legal code and it works as assumed. – Luis Colorado Dec 29 '18 at 12:47

2 Answers2

2

Having more than one return statement has nothing to do with the error you are getting. In your case,

if (N == 1)
    return 1;
return N + MSum(N - 1);

is same as

if (N == 1)
{                        //block starts
    return 1;
}                       //block end
return N + MSum(N - 1);

so, the return 1; statement in under the conditional block, and executes only if the condition is met.

Regarding the error you are seeing, this may help.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

The meaning of the function is to sum up all numbers from 1 to N, where N is the parameter passed. The function calls itself recursively, when N != 1, to achieve the sum... by adding N to the sum of the numbers up to N-1. By the way, the code you posted compiles and runs perfectly in my system (without any touching) so probably you have not tested the code you posted, and it's not the same as the code you have tested. Try compiling by:

cc -o pru pru.c

where pru is the program name, and pru.c is the file in which you have the code.

It's an exercise to test how recursive functions can be used in C. But if you don't know that you can use two different return statements in the same function, you are trying to go too quickly in the learning of C language. Recursion in C is more advanced than the return statement. I can recommend you to read "The C programming language", from Brian Kernighan and Dennis Ritchie.

Luis Colorado
  • 10,974
  • 1
  • 16
  • 31