1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

[TuT] Recursive function to reverse an array of characters

Discussion in 'C, C++, C#' started by Juni0r_r00t, Aug 24, 2009.

  1. Juni0r_r00t

    Juni0r_r00t Newbie

    Joined:
    Aug 23, 2009
    Messages:
    3
    Likes Received:
    0
    Occupation:
    Programmer
    Home Page:
    Hi,

    This code causes the reversal of an array of characters using a recursive function.



    Code:
    #include <stdio.h>
    
    void inv(char *string)
    {
    if(*string)
    {
    inv(string+1);
    putchar(*string);
    }
    }
    int main()
    {
    inv("kleber");
    return 0;
    } 

    Explaining:




    int main ()
    (
    inv ( "linux"); / / when you call the function passing a string inv
    / / she attaches to the str pointer memory address
    / / the first character of string ..... in this case 'l'
    return 0;
    )

    void inv (char * str)
    (
    if (* str) / / if the contents of the pointer "* str" is different from 0 ..........
    (
    inv (str +1); / / sum 1 in memory location
    / / the program calls the function again
    / / address of the next character as a parameter
    putchar (* str) / / when he leaves if thereby ending
    / / function it is returning the characters
    / / pending and so is q it shows the opposite ...
    )
    )
     
  2. _Austin

    _Austin Junior Member

    Joined:
    Apr 9, 2009
    Messages:
    147
    Likes Received:
    39
    Nice little tut, I'm sure it could be useful for someone. I suggest you put the comments in the actual code block instead of just redoing it all below.

    _Austin