C Programming GATE Question Answers with Explanation.
Q1 – Consider the following ANSI C program. (GATE 2021 SET 1)
#include
int main()
{
int i, j, count;
count = 0;
i=0;
for (j = -3; j <= 3; j++)
{
if (( j >= 0) && (i++))
count = count + j;
}
count = count +i;
printf(“%d”, count);
return 0;
}
Which one of the following options is correct?
The program will not compile successfully
The program will compile successfully and output 10 when executed
The program will compile successfully and output 8 when executed
The program will compile successfully and output 13 when executed
Ans – (2)
Explanation –
Let’s analyze the code
i starts at 0.
The for loop iterates for j from -3 to 3.
Inside the loop, i increments only when j is non-negative.
The value of j is added to count only when j is non-negative.
After the loop, the final value of i is added to count.
Let’s go through the loop:
When j is 0, i increments to 1, and count becomes 0.
When j is 1, i increments again to 2, and count becomes 1.
When j is 2, i increments again to 3, and count becomes 3.
When j is 3, i increments again to 4, and count becomes 6.
After the loop, the final value of i is 4, so count becomes 10.
Therefore, the correct option is
The program will compile successfully and output 10 when executed.
Q2 – Consider the following ANSI C function: (GATE 2021 Set 1)
int SimpleFunction(int Y[], int n, int x)
{
int total = Y[0], loopIndex;
for (loopIndex = 1; loopIndex <= n-1; loopIndex++)
total = x*total + Y[loopIndex];
return total;
}
Let Z be an array of 10 elements with Z[i]=1, for all i such that 0 ≤ i ≤ 9. The value returned by SimpleFunction(Z, 10, 2) is __________ .
Ans – (1023)
Explanation –
You have an array Z with 10 elements where each element Z[i] = 1 for 0 ≤ i ≤ 9. You’re calling SimpleFunction(Z, 10, 2).
Let’s calculate the value returned by SimpleFunction
n is 10, so the loop runs from loopIndex = 1 to loopIndex = 9.
total initially takes the value of Y[0], which is Z[0], so total = 1.
Then, the loop iterates from loopIndex = 1 to loopIndex = 9:
In each iteration, total gets updated as x * total + Y[loopIndex].
For x = 2, the formula becomes total = 2 * total + 1.
total gets updated iteratively through each loop iteration.
Let’s calculate the value step by step:
loopIndex = 1: total = 2 * total + 1 = 2 * 1 + 1 = 3
loopIndex = 2: total = 2 * total + 1 = 2 * 3 + 1 = 7
loopIndex = 3: total = 2 * total + 1 = 2 * 7 + 1 = 15
loopIndex = 4: total = 2 * total + 1 = 2 * 15 + 1 = 31
loopIndex = 5: total = 2 * total + 1 = 2 * 31 + 1 = 63
loopIndex = 6: total = 2 * total + 1 = 2 * 63 + 1 = 127
loopIndex = 7: total = 2 * total + 1 = 2 * 127 + 1 = 255
loopIndex = 8: total = 2 * total + 1 = 2 * 255 + 1 = 511
loopIndex = 9: total = 2 * total + 1 = 2 * 511 + 1 = 1023
Therefore, the value returned by SimpleFunction(Z, 10, 2) is 1023.