Saturday, 25 February 2017

GATE EXAM PREPARATION IN "C" - Choose the correct option to fill

Choose the correct option to fill ?1 and ?2 so that the program below prints an input string in reverse order. Assume that the input string is terminated by a newline character.
void reverse(void)
 {
  int c;
  if (?1) reverse() ;
  ?2
}
main()
{
  printf ("Enter Text ") ;
  printf ("\n") ;
  reverse();
  printf ("\n") ;
}

(A) ?1 is (getchar() != ’\n’)
?2 is getchar(c);
(B) ?1 is (c = getchar() ) != ’\n’)
?2 is getchar(c);
(C) ?1 is (c != ’\n’)
?2 is putchar(c);
(D) ?1 is ((c = getchar()) != ’\n’)
?2 is putchar(c);
Answer(D)
getchar() is used to get the input character from the user and putchar() to print the entered character, but before printing reverse is called again and again until ‘\n’ is entered. When ‘\n’ is entered the functions from the function stack run putchar() statements one by one. Therefore, last entered character is printed first.
You can try running below program
void reverse(void); /* function prototype */
 
void reverse(void)
 {
  int c;
  if (((c = getchar()) != '\n'))
    reverse(); 
  putchar(c);
}
main()
{
  printf ("Enter Text ") ;
  printf ("\n") ;
  reverse();
  printf ("\n") ;
  getchar();
}

No comments:

Post a Comment