Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

recursion c, program does not display

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));
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading