13,501,644 members
See more:
This C program will take the value stored in the variable a and print them one by one.

```#include <stdio.h>
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,`

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?

What I have tried:

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,`
Posted 19-May-17 9:42am
Updated 19-May-17 10:36am

## Solution 1

Quote:
Can someone please explain how this program works:

Why explain to you with words when you can see by yourself what is doing the program and how. Use the debugger, it is an incredible learning tool.

When you don't understand what your code is doing or why it does what it does, the answer is debugger.
Use the debugger to see what your code is doing. Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.

Debugger - Wikipedia, the free encyclopedia[^]
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't find bugs, it just help you to. When the code don't do what is expected, you are close to a bug.

Top Experts
Last 24hrsThis month
 OriginalGriff 134 CPallini 80 Jochen Arndt 75 John Simmons / outlaw programmer 60 Richard MacCutchan 53
 OriginalGriff 3,765 Jochen Arndt 2,268 ppolymorphe 1,817 Maciej Los 1,649 Wendelius 1,480