Click here to Skip to main content
13,192,207 members (36,045 online)
Rate this:
 
Please Sign up or sign in to vote.
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

1 solution

Rate this: bad
 
good
Please Sign up or sign in to vote.

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.
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy |
Web03 | 2.8.171017.2 | Last Updated 19 May 2017
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100