Can anyone explain this program

#include<stdio.h>
void f(int n, int s)
{
int k=0,j=0;
if (n==0)return;
k=n%10;
j=n/10;
s+=k;
f(j,s);
printf("%d,",k);
}
main()
{
int a=2048,s=0;
f(a,s);
printf("%dn",s);
}

It finds the sum of digits in 2048. But it won’t work unless you call by reference.

2 Likes

This code prints the digits in the number using recursion. You tried to print sum of all the digits too but you are calling the function using call by value which will not change the value of s. Use call by reference method to get the desired output.

The output is something else, pls run it first.

I know it prints digits (separated by commas) followed by sum. But sum is 0 because you didn’t perform call by reference.

Try this (comments below):

#include<stdio.h>
void f(int n, int s) // *s instead of s
{
int k=0,j=0;
if (n==0)return;
k=n%10;
j=n/10;
s+=k; // *s=*s+k;
f(j,s);
printf("%d,",k);
}
main()
{
int a=2048,s=0;
f(a,s); // Pass &s
printf("%dn",s);
}

1 Like