Thread: Output

  1. #1
    Registered User
    Join Date
    Aug 2012
    Posts
    1

    Output

    Why the output of this code is 15? Please do write the explaination also.

    Code:
    #include <stdio.h>
    int f(int *a, int n)
    {
    if(n<=0)return 0;
    else if( *a % 2 == 0) return *a + f(a+1,n-1);
    else return *a -f(a+1,n-1);
    }
    int main()
    {
    int a[]={12,7,13,4,11,6};
    printf("%d",f(a,6));
    return 0;}

  2. #2
    Registered User
    Join Date
    Apr 2008
    Posts
    396
    Apply the recursion: 12 + (7 - (...)) = 15
    I let you guess what's left.
    Last edited by root4; 08-12-2012 at 03:42 AM.

  3. #3
    Registered User
    Join Date
    Dec 2011
    Posts
    795
    > Please do write the explaination also.
    Is this a homework assignment? Or did you just find code and are confused about the result.

    Before the code is explained, it should be formatted better so it's easier to follow what's going on:
    Code:
    #include <stdio.h>
    
    
    int f (int *a, int n)
    {
        if (n <= 0)
            return 0;
        else if ((*a % 2) == 0)
            return *a + f(a + 1, n - 1);
        else
            return *a - f(a + 1, n - 1);
    }
    
    
    int main ()
    {
        int a[] = {12, 7, 13, 4, 11, 6};
        printf("%d", f(a, 6));
        return 0;
    }
    Now, go through each step of the program and note the variables each time. Start with something like this:

    function call *a n return of f
    f(a, 6) 12 6 12 + f(a + 1, n - 1)
    f(a + 1, n - 1) 7 5 7 - f(a + 1, n - 1)
    f(a + 1, n - 1) 13 4 13 - f(a + 1, n - 1)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C++ overlapping output and adding extensions to output files
    By lordmorgul in forum Linux Programming
    Replies: 9
    Last Post: 05-11-2010, 08:26 AM
  2. How to edit output in struct and call for the output
    By andrewkho in forum C Programming
    Replies: 4
    Last Post: 03-16-2010, 10:28 PM
  3. terminal output not showing output properly
    By stanlvw in forum C Programming
    Replies: 13
    Last Post: 11-19-2007, 10:46 PM
  4. output a string to a standard output
    By sh4k3 in forum C Programming
    Replies: 3
    Last Post: 06-15-2007, 05:59 AM
  5. Replies: 3
    Last Post: 02-19-2003, 08:34 PM