Home > Back-end >  Simple C program and understanding the output
Simple C program and understanding the output

Time:11-22

I gonna have exam from C next week. I will have to type, what is the output of given C programs. We also get some examples of those programs, to know what to prepare for. Unfortunately i don't have too much time to dive deep in C now so what i'm trying to do is just get some general knowledge.

So i have the given program:

#include <stdio.h>
int A[] = {1,2,3,5,7,11,13,17,19};
#define MaxJ (sizeof A / sizeof A[0]-1)

int tot(int j)
{
    if (2*j <= MaxJ)
        return tot(2*j)   tot(2*j 1);
    else if (j<=MaxJ)
        return A[j];
    else return 0;
}
int main()
{
    printf("%d", tot(1));
    return 0;
}

The question is, what exactly happens in that 'if' statement? I understand that MaxJ is 8 and why, but the output 60 confuses me. From what i thought is that we passes value 1 as an argument to tot(), then multiplaying that 1 by 2 till we get 16 which is > MaxJ so we go to else if and return A[j], which should be 19 for j = 8. But that's not correct.

CodePudding user response:

If you add some debug printfs you can see what is going on:

int A[] = {1,2,3,5,7,11,13,17,19,20,21,22,23,24,25,26,27,28};
#define MaxJ (sizeof A / sizeof A[0]-1)

int tot(int j)
{
    if (2*j <= MaxJ)
    {
        printf(" >>>> j = %d 2*j = %d\n", j, 2*j);
        return tot(2*j)   tot(2*j 1);
    }
    else 
    if (j<=MaxJ)
    {
        printf("j = %d A[j] = %d\n", j, A[j]);
        return A[j];
    }
    else return 0;
}
int main()
{
    printf("MAXJ = %zu\n", MaxJ);
    printf("%d", tot(1));
    return 0;
}

Analyzing it you will discover that the function is returning the sum of the upper half array elements (if number of elements is odd then that half is larger by one than the lower half)

  •  Tags:  
  • c
  • Related