Thread: Understanding an exercise

  1. #1
    Registered User
    Join Date
    Jan 2013
    Posts
    108

    Understanding an exercise

    hi all,

    I have this code below and i'm trying to understand it.
    It's a code i took from an exercise and i need to analyze it.
    Can someone guide me on understanding it?
    Code:
    void fun(int);
    typedef int (*pf) (int, int);
    int proc(pf, int, int);
    
    int main()
    {
    int a=3;
    fun(a);
    return 0;
    }
    void fun(int n)
    {
    if(n > 0)
    {
    fun(--n);
    printf("%d,", n);
    fun(--n);
    }
    }
    from what i understand and i'm guessing i'm wrong:
    a=3
    if a>0 then fun(--a) --> in that case a should already be 2 right?
    then i need to print 2 i get stuck here

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Start by posting it in plain text, with proper indentation, and the required header so it's easy to read, compile and run:
    Code:
    #include <stdio.h>
    
    
    void fun(int);
    typedef int (*pf) (int, int);
    int proc(pf, int, int);
    
    
    int main()
    {
        int a=5;
        fun(a);
        return 0;
    }
    
    void fun(int n)
    {
        if(n > 0)
        {
            fun(--n);
            printf("%d,", n);
            fun(--n);
        }
    }
    Next, trace it by hand. This is a pain, and will likely involve lots of paper and pencil work, and a bit of time, but is excellent for helping you understand what code is doing. The more you practice this, the easier it gets to trace code and make sense of it in your head.

    You're correct that fun(--n) calls fun with a value of 2 the first time (n was 3, and decremented before the function call), but when you call a function, even if called recursively, you start at the beginning of the function again. So you have to go back to line 15 (in my version) and check if (n > 0) for n==2, and go from there. Only when you're all done with the recursion (base case of if (n > 0) fails), will you begin to return from the recursive calls to fun(), and the printf will be executed. Note too, that after you print, you do another recursive call to fun, decrementing n again before the call.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Understanding an exercise
    By YannB in forum C Programming
    Replies: 5
    Last Post: 01-20-2014, 02:47 PM
  2. An exercise from K&R
    By GL.Sam in forum C Programming
    Replies: 4
    Last Post: 05-07-2010, 09:31 AM
  3. Exercise 2-6 K&R help
    By allix in forum C Programming
    Replies: 19
    Last Post: 08-18-2006, 09:25 AM
  4. Exercise
    By bumfluff in forum C++ Programming
    Replies: 15
    Last Post: 04-21-2006, 12:18 PM
  5. Help with K&R Exercise 1.13
    By Yannis in forum C Programming
    Replies: 2
    Last Post: 09-21-2003, 02:51 PM