C Programming - Strings - Discussion

Discussion Forum : Strings - Find Output of Program (Q.No. 6)
6.
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);
}
abc abc
bca
Infinite loop
cba
Answer: Option
Explanation:

Step 1: void fun(); This is the prototype for the function fun().

Step 2: fun(); The function fun() is called here.

The function fun() gets a character input and the input is terminated by an enter key(New line character). It prints the given character in the reverse order.

The given input characters are "abc"

Output: cba

Discussion:
31 comments Page 2 of 4.

Priyanka said:   1 decade ago
Its an recursion.
In recursion stack fill as like staircase.

So as by it executing stack become empty.
As stack empty it is in FILO means which is first in is get last out.

So it prints reverse.

Chandu said:   9 years ago
In the recursive call every time stack allocates a memory and store the values, here on the failure of condition pointer must be go back to main so at this time it prints reversely.
(2)

Pravas said:   10 years ago
Answer is cba because, in the loop if((c=getchar()!="\n").

That means output character should not c ="\n" that is a (c!=a), so, first c is printed then b then a.

Manali said:   2 decades ago
Can you explain it to me. It took abc alltogether as an input, then printf will print it in reverse order? I am unable to understand it.

Manish said:   1 decade ago
@Shubh.

getchar() will take one character as input and matches it with \n and then make a recursive call if condition is satisfied.

Shubham said:   8 years ago
Fun() function declared in main function. How it is accessible by fun() Only main function can call it. Correct me if I am wrong.

Laxmi said:   7 years ago
%c prints only single char. Then how it prints cba. Please explain me how the program executes?

Anjan said:   1 decade ago
How %c can printing 3 value. I know it is childish question but please help me.

Anshul Jain said:   10 years ago
I run this program in turbo c++.

My answer is (null).

Any one explain me?

Durai said:   1 decade ago
How come 'char c' prints three characters continuously as array?


Post your comments here:

Your comments will be displayed after verification.