Thread: Recursion

  1. #1
    Registered User
    Join Date
    Aug 2009
    Posts
    27

    Recursion

    This program suppose to count the string length that are A-Z,a-z, and 0-9 using recursion but it counts everything, why??

    Code:
    #include <stdio.h>
    
    int count(char string[])
    {
        int i = 0;
    
        if(string[i] == 0)
        {
            return 0;
        }
    
        else if((string[i]>=48)||(string[i]<=57)||(string[i]>=65)||(string[i]<=90)||(string[i]>=97)||(string[i]<=122))
        {
            printf("%d\n",string[i]);
            return (1 + count(&string[i+1]));
    
        }
    
        else
        {
            return 0;
        }
    }
    
    int main()
    {
        char buffer[64];
        char string[64];
        int i = 0;
        int len = 0;
    
        printf("Enter string: ");
        fgets(buffer,63,stdin);
        sscanf(buffer,"%s",string);
    
        len = count(&string[i]);
        printf("Length: %d\n",len);
    }

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Check the condition of your recursive step; it is not quite right.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Make Fortran great again
    Join Date
    Sep 2009
    Posts
    1,413
    ((string[i]>=48)||(string[i]<=57)||(string[i]>=65)||(string[i]<=90)||(string[i]>=97)||(string[i]<=122))

    probably need some &&s in there, cause right now any ASCII character will return true for that statement...

  4. #4
    Registered User
    Join Date
    Aug 2009
    Posts
    27
    Thanks a lot

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Template Recursion Pickle
    By SevenThunders in forum C++ Programming
    Replies: 20
    Last Post: 02-05-2009, 09:45 PM
  2. Recursion... why?
    By swgh in forum C++ Programming
    Replies: 4
    Last Post: 06-09-2008, 09:37 AM
  3. a simple recursion question
    By tetra in forum C++ Programming
    Replies: 6
    Last Post: 10-27-2002, 10:56 AM
  4. stack and recursion help needed!
    By LouB in forum C++ Programming
    Replies: 3
    Last Post: 07-01-2002, 02:19 PM
  5. selection sorting using going-down and going-up recursion
    By Unregistered in forum C Programming
    Replies: 1
    Last Post: 11-02-2001, 02:29 PM