Thread: while loop vs recursive

  1. #1
    Unregistered
    Guest

    while loop vs recursive

    Dear All,

    How can I change the while loop into recursive?

    /*function to count the characters in a string */

    int string_length (char *string)
    {
    char *cptr = string;

    while (*cptr)
    ++cptr;
    return (cptr - string);
    }
    main()
    {
    int string_length (char *string);
    printf("%i ", string_length ("string_length test"));
    }

  2. #2
    Im a Capricorn vsriharsha's Avatar
    Join Date
    Feb 2002
    Posts
    192

    Thumbs up

    Try this out...
    Im not sure if it would work but just try n see...


    int str_len(char *s)
    {

    static int i;
    if(*s!='\0')
    {
    s++;
    i+=str_len(s);
    }
    return(i);
    }


    Regards,
    Sriharsha.
    Help everyone you can

  3. #3
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >Im not sure if it would work but just try n see...
    That doesn't work, this will work the first time. See if you can figure out the problem with a recursive strlen.
    Code:
    int getlen ( char *s )
    {
      static int i = 0;
      if ( *s++ != '\0' )
        getlen ( s );
      return ( i++ );
    }
    Time's up! Did you see it? The i variable is declared as static so that it will hold a value as each new instance of getlen is pushed onto the stack. When getlen is exited altogether, i still keeps the same value. Any successive calls to this function will result in the number of characters in the string plus the total length of all strings calculated before it (minus the NUL terminators).

    While it is possible to get around this problem, it's just not worth the effort since an iterative solution is simpler and will produce accurate output with every function call.

    -Prelude
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Visual Studio Express / Windows SDK?
    By cyberfish in forum C++ Programming
    Replies: 23
    Last Post: 01-22-2009, 02:13 AM
  2. Personal Program that is making me go wtf?
    By Submeg in forum C Programming
    Replies: 20
    Last Post: 06-27-2006, 12:13 AM
  3. A somewhat bizzare problem!!! - WHILE LOOP
    By bobthebullet990 in forum C Programming
    Replies: 3
    Last Post: 03-31-2006, 07:19 AM
  4. when a while loop will stop ?
    By blue_gene in forum C Programming
    Replies: 13
    Last Post: 04-20-2004, 03:45 PM
  5. How to change recursive loop to non recursive loop
    By ooosawaddee3 in forum C Programming
    Replies: 1
    Last Post: 06-24-2002, 08:15 AM