Discussion
What is the output of the following program ?
#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(void)
{
int a[] = {12, 7, 13, 4, 11, 6};
printf("%d", f(a,6));
return 0;
}
Answer: C
The program prints 15.
f adds an even element and subtracts the result of the rest after an odd element. Work from the end of the array {12, 7, 13, 4, 11, 6}:
\[ \begin{aligned} f(\{6\}) &= 6 + 0 = 6 \\ f(\{11,6\}) &= 11 - 6 = 5 \\ f(\{4,\ldots\}) &= 4 + 5 = 9 \\ f(\{13,\ldots\}) &= 13 - 9 = 4 \\ f(\{7,\ldots\}) &= 7 - 4 = 3 \\ f(\{12,\ldots\}) &= 12 + 3 = 15 \end{aligned} \]
The trap is reading it as an alternating sum of the elements; the subtraction applies to the whole remaining result, not to the next element alone. 5 is the value at the 11 step, and -9 and 19 come from sign slips.
Post your comment
Please log in or register to post a comment.
Examination Categories
- SSC Exams
- Banking Exams
- Teaching Exams
- Civil Services Exams
- Railways Exams
- Engineering Recruitment Exams
- Defence Exams
- State Government Exams
- Police Exams
- Insurance Exams
- Nursing Exams
- Other Government Exams
- NRA CET
- PG Entrance Exams
- Campus Placement
- MBA Entrance Exams
- CUET and UG Entrance
- Judiciary Exams
- Regulatory Body Exams
- Software Development