2,244 views
4 4 votes

What will be the output of the program If characters 'a', 'b' and 'c' enter are supplied as input?

#include<stdio.h>

int main()
{
    void fun();
    fun();
    printf("\n");
    return 0;
}
void fun()
{
    char c;
    if((c = getchar())!= '\n')
        fun();
    printf("%c", c);
}
[A]. abc abc
[B]. bca
[C]. Infinite loop
[D]. c,b,a

1 Answer

0 0 votes

Suppose input is given from the keyboard: When you give 'a' as input and press enter,

getchar() returns the first character in the input buffer (i.e. c = 'a'), and removes it from the input buffer. But other character (i.e. '\n') is still in the input buffer. c is checked with '\n' 'a' != '\n' and fun() is called again but now '\n' was already present in the input buffer so c = '\n'. The condition is checked again to be false. Thus '\n' is printed followed by 'a' from first call to fun(), followed by '\n' from main().Output: 2 lines first blank second has character a

'\n'--> blank line

a

If input is given as abc then '\n' Output: 2 lines first blank second has characters cba

'\n' --> blank line

cba

Position:
Show:

Related questions

1 1 vote
1 1 answer
168
168 views
khanshahima4 asked Sep 24
168 views
1. If precedence tells me which operator has priority, and associativity tells me how to handle operators at the same level, then why do I need a separate concept called ...
13 13 votes
1 1 answer
1.3k
1.3k views
GO Classes asked Jul 2
1,265 views
Assume:$\texttt{short = 2 bytes}$, $\texttt{int = 4 bytes}$, $\texttt{char = 1 byte}$$\texttt{int}$ needs $4$-byte alignment and the final structure size is rounded to a ...
16 16 votes
2 2 answers
682
682 views
GO Classes asked Jul 2
682 views
Assume:struct Student { double gpa; }; struct Student alice; struct Student *sptr = &alice;Which of the following correctly assigns $\texttt{4.0}$ to $\texttt{alice.gpa}$...
9 9 votes
1 1 answer
505
505 views
GO Classes asked Jul 2
505 views
Consider the following code idea from the source:typedef struct { double x, y; } Point; void reset(Point p) { p.x = p.y = 0; } int main() { Point a = {12.0, 42.0}; Point ...