Thread: Can someone please explain to me the logic behind the output of this function?

  1. #1
    Registered User
    Join Date
    Jun 2016
    Posts
    16

    Post Can someone please explain to me the logic behind the output of this function?

    Input: abcd
    Output: dcba
    Code:
    #include<stdio.h>
    #include<stdlib.h>
    
    
    void mystery(void);
    
    
    main()
    {
        mystery();
    }
    void mystery(void)
    {
        int c;
        if((c=getchar()) != EOF){
            mystery();
            putchar(c);
        }
    }
    Last edited by SauceGod; 07-15-2016 at 03:23 PM.

  2. #2
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    1,110
    Very simple!

    The program uses recursion to reverse the string entered.

    main() calls mystery()
    getchar() gets the first character
    mystery() then calls itself
    getchar() gets the second character
    mystery() then calls itself
    getchar() gets the third character
    ...
    When no more characters to get,
    putchar() displays the last character retrieved.
    mystery() returns to the calling function, mystery()
    putchar() displays the previous character retrieved.
    mystery() returns to the calling function, mystery()
    ...
    Until all characters have been displayed, and control returns to main().
    The program exits main() and returns to the O/S.

    In each separate call to mystery() a new and different integer 'c' is created, containing each one of the characters entered.
    I would not want to redirect the text from "War & Peace" into this program as you would blow the stack! There is no control here as to the maximum level of recursion allowed! ;^)
    If the input is coming from the command line it would require the user to press [Ctrl-D] on a Linux/UNIX system, or [Ctrl-Z] on a Windows/DOS system to force the EOF!

    In other words, this simple program could use some improvement.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Would anyone please explain me this logic ?
    By CChakra in forum C++ Programming
    Replies: 4
    Last Post: 02-19-2014, 11:27 AM
  2. Replies: 3
    Last Post: 01-16-2014, 09:58 AM
  3. Replies: 10
    Last Post: 06-09-2012, 11:55 AM
  4. Can someone explain the logic of the program
    By chibi.coder in forum C Programming
    Replies: 5
    Last Post: 12-25-2011, 09:23 AM
  5. Replies: 2
    Last Post: 10-14-2009, 07:45 AM

Tags for this Thread