retagged by
530 views
3 votes
3 votes
#include<stdio.h>
int bar(int data[], int i, int a, int x) {
    if (x<0) return 0;
    x--;
    int b = a + data[i];
    if(data[i] >0) return bar(data, i+1, b, x);
    if(data[i] == 0 || i ==x-1) return a;
    return -a;
}
int main()
{
    int data[5] = {1,2,3, -1};
    int x = (int *)(&data+1)-data;
    printf("%d", bar(data, 0, 0, x) );
}

What will be the output of a given program?

  1. $6$
  2. $-6$
  3. $0$
  4. $5$
retagged by

1 Answer

6 votes
6 votes
1 2 3 -1 0  
1000 1004 1008 1012 1016 1020

this is data[5]; data is a pointer to an int having address of 1 ie 1000 and &data is a pointer to an int array of size 5 having address equal to base address of array ie 1000; (&data+1) = 1020.

therefore, x = 5;

Following is the sequence of function calls made; conditions that affect program flow are underlined and all variable value changes are bold.

  1. bar( data, 0, 0, 5 ) → here i=0, a =0, x=5, x not < 0; x – –; thus x=4; b = 0 + data[0] = 1data[0] > 0; nextcall
  2. bar( data, 1, 1, 4 ) → here i=1, a =1, x=4, x not < 0; x – –; thus x=3; b = 1 + data[1] = 3data[1] > 0; nextcall
  3. bar( data, 2, 3, 3 ) → here i=2, a =3, x=3, x not < 0; x – –; thus x=2; b = 3 + data[2] = 6data[2] > 0; nextcall
  4. bar( data, 3, 6, 2 ) → here i=3, a =6, x=2, x not < 0; x – –; thus x=1; b = 6 + data[3] = 5data[3] not > 0; ( data[i] not = 0 || i not = (2-1) ); return – a

Answer :- B. – 6

Answer:

Related questions

5 votes
5 votes
1 answer
1