Tahir Mammadli
Tahir Mammadli

Reputation: 1

Issue with recursion in C++

Why is it not counting properly? I'm so confused why is it printing the string with 0's in it? I just want to count the number of uppercase letters and output them.

#include <iostream>

void uppercase(const char *str){
    //std::vector<char> strVector;
    int counter = 0;
    if(str[0]){
        if(isupper(str[0])) counter++;
        uppercase(str+1);
    }
     std::cout<<counter;
}
int main(){
   uppercase("United States of America");

}

the output:

0000000100000000010000001

Upvotes: 0

Views: 58

Answers (2)

cigien
cigien

Reputation: 60228

The main issue in your function is that you are printing out whether a char is uppercase or not. Instead, you should make the function return an int, and recursively call the function with the next substring:

int uppercase(const char *str) {
    if(str[0]) {                    // while not reached the end of the string 
        return !! isupper(str[0])   // add 1 if uppercase 
               + uppercase(str+1);  // recursively call with suffix of string
    }
    return 0;  // base case
}

and now you can simply print the returned result:

int main(){
  std::cout << uppercase("United States of America");
}

Here's a demo.

Note that the !! is just a shorter syntax that converts the result if isupper to a bool and then back to an int. This is equivalent to isupper(str[0]) ? 1 : 0.

Upvotes: 3

WhozCraig
WhozCraig

Reputation: 66194

Your calculation function should be doing just that: calculating (i.e. not printing anything). Instead, it should return the number and have the original caller take the final step of printing.

E.g.

#include <iostream>

int uppercase(const char *str)
{
    if (*str) 
        return (isupper(*str) ? 1 : 0) + uppercase(str+1);
    return 0;
}

int main()
{
   std::cout << uppercase("United States of America") << '\n';
}

Upvotes: 2

Related Questions