C Programming GATE Question Answers with Explanation.
Q1 – The integer value printed by the ANSI-C program given below is. (GATE 2023)
Â
#include<stdio.h>
int funcp(){
     static int x = 1;
     x++;
     return x;
}
int main(){
     int x,y;
     x = funcp();
     y = funcp()+x;
     printf(“%d\n”, (x+y));
     return 0;
}Â
Ans – (7)
Explanation –
The code provided contains a function funcp() and the main() function in C programming.
Let’s break down the code and its execution
funcp() is a function that returns an incremented value of the static variable x each time it’s called.
In main(), x is assigned the value returned by funcp(), which is initially 2 (x = funcp()).
y is assigned the value obtained by calling funcp() again (resulting in x being incremented to 3) and adding it to the current value of x, making y = 2 + 3 = 5.
The printf() statement prints the sum of x and y, so it outputs 2 + 5 = 7.
Therefore, the output of the code will be 7.
Q2 – Consider the C function foo and the binary tree shown. (GATE 2023)
Â
typedef struct node {
int val;
struct node *left, *right;
} node;
int foo(node *p) {
int retval;
if (p == NULL)
   return 0;
else {
   retval = p->val + foo(p->left) + foo(p->right);
   printf(“%d “, retval);
   return retval;
}
}
When foo is called with a pointer to the root node of the given binary tree, what will it print?
 3 8 5 13 11 10
 3 5 8 10 11 13
 3 8 16 13 24 50
 3 16 8 50 24 13
Ans – (3)
Explanation –
Let’s analyze the code and evaluate what it will print when `foo` is called with a pointer to the root node of the given binary tree.
Given binary tree:
“`
10
/ \
5 11
/ \ \
3 8 13
“`
Now, let’s walk through the code execution:
1. When `foo` is called with the root node (10), it calculates `retval = 10 + foo(5) + foo(11)`.
2. For the left subtree (5):
– `retval = 5 + foo(3) + foo(8)`.
– For the left child (3), `retval = 3 + foo(NULL) + foo(NULL)`.
– For the right child (8), `retval = 8 + foo(NULL) + foo(NULL)`.
3. For the right subtree (11):
– `retval = 11 + foo(NULL) + foo(13)`.
Now, let’s substitute the values back into the original call:
“`
retval = 10 + (5 + (3 + 0 + 0) + (8 + 0 + 0)) + (11 + 0 + (13 + 0 + 0))
“`
Simplifying further:
“`
retval = 10 + (5 + 3 + 8) + (11 + 13)
retval = 10 + 16 + 24
“`
So, the value of `retval` is 50.
Now, the `printf(“%d “, retval);` statement will print `50` when `foo` is called with the root node.
Therefore, the correct option is
C. 3 8 16 13 24 50