Discussion
Consider the following C program:
#include \(\lt\)stdio.h\(\gt\)
void fX();
int main(){
fX();
return 0;}
void fX(){
char a;
if((a=getchar()) != ’\n’)
fX();
if(a != ’\n’)
putchar(a);}
Assume that the input to the program from the command line is 1234 followed by a newline character. Which one of the following statements is CORRECT?
Answer: C
The program terminates with 4321 as output.
Each call to fX reads one character into its own local variable a. If it is not a newline, it calls fX again before printing. So the calls nest: the first reads '1', the second '2', the third '3', the fourth '4', and the fifth reads the newline and does not recurse.
Now the calls return in reverse order. The fifth call holds the newline and prints nothing. The fourth prints '4', the third '3', the second '2' and the first '1'. Output: 4321. The recursion depth is bounded by the input length, so the program terminates, and it does produce output; printing happens after the recursive call, which is why the order is reversed rather than 1234.
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