This C program will take the value stored in the variable a and print them one by one.
#include
void foo(int n, int sum)
{
int k = 0, j = 0;
if (n == 0)
return;
k = n % 10;
j = n / 10;
sum = sum + k;
foo (j, sum);
printf ("%d, ", k);
}
int main ()
{
int a = 2048, sum = 0;
foo (a, sum);
printf("\n");
return 0;
}
Output:
2, 0, 4, 8,
When the function foo executes:
1) For the first time: n = 2048, k = 8, j = 204, sum = 8
2) For the second time: n = 204, k = 4, j = 20, sum = 12
3) For the third time: n = 20, k = 0, j = 2, sum = 12
4) For the fourth time: n = 2, k = 2, j = 0, sum = 14
If I replace the line (present in the foo function):
printf ("%d, ", k);
with this:
printf ("%d | %d, ", k, sum);
Output:
2 | 14, 0 | 12, 4 | 12, 8 | 8,
Can someone please explain how this program works:
1) How it's printing value stored in a?
2) And in this order: 2, 0, 4, 8, ?
3) Why is the value of sum is changing when we're printing values of k?
Answers
Answered by
0
the given program is used for calculating the sum of the digits of no. 2048.
here in the first call of foo() function the variable a changes to 204 in the second call and so on.
secondly, in the last call, the foo function will simply print the 1st digit of no 2048. and then 0 and so on.
lastly, the value of k changes as we printing the value of k (digit position) and the sum of the digits till that position (variable sum)...
Hope this helps you to understand the flow of the program...:)
here in the first call of foo() function the variable a changes to 204 in the second call and so on.
secondly, in the last call, the foo function will simply print the 1st digit of no 2048. and then 0 and so on.
lastly, the value of k changes as we printing the value of k (digit position) and the sum of the digits till that position (variable sum)...
Hope this helps you to understand the flow of the program...:)
Similar questions
Social Sciences,
8 months ago
Social Sciences,
8 months ago
Science,
1 year ago
Computer Science,
1 year ago