Home > Back-end >  recursion c, program does not display
recursion c, program does not display

Time:12-07

im facing an problem in this program, may anyone tell me, what im doing wrong, the program won't display anything after i give it input. (Code is about sum of digits enter #example 12345 = 15)

#include<stdio.h>
int sum(int num);

int sum(int num){
int total=0;
if(sum==0){
    return total;
}
else{
    total =num%10;
    num/=10;
    return sum(num);
}
}

int main()
{
int num,k;
printf("Enter 5 positive number: ");
scanf("%d",&num);
printf("Sum is: %d",sum(num));
}

CodePudding user response:

Here is a rule of thumb, whenever you have a non-stopping recursion program try to verify your base cases.

Here you are verifying sum the function instead of num the parameter. The C compiler let's you do that because functions in C are pointers, and pointers hold the addresses as numeric value.

CodePudding user response:

You just need to change the condition from sum==0 to num==0. It will now print something. However, the logic of your program is still wrong. You can change your sum function to this.

int sum(int num){
    if(num==0) {
        return 0;
    }
    return num % 10   sum(num/10);
}

And you can try learning more about recursion through stack since recursion is basically just stack.

  • Related