简体   繁体   中英

counting upper case letters in recursive function

i know this is wrong, however just learning how to do recursive functions and trying to understand how to work this out better.

    #include <iostream>
   using namespace std;


    int getUpper ( const string& s, int high) {

      int count=0;


       if(s.size()>0) {

         if (s[0] <='Z' && s[0] >='A') 
          count++;

       return getUpper(s.substr(1,s.size()-1), high-1);

    }
     return count;
 }

     int getUpper (const string& s){
         int high=s.size()-1;

        int count=getUpper(s,high);
      return count;
   }


   int main()
  {
     string s="WeLC";
    int value=getUpper(s);
    cout << value;
      return 0;
  }

Why is this not returning the count number? of 4.

One hint: getUpper returns the value without incorporating the count .

return getUpper(s.substr(1,s.size()-1), high-1); // no `count`

BTW, getUpper("WeLC") should return 3 , not 4 .

Realize that each recursive invocation of getUpper has its own copy of the local variable count . count++ doesn't do anything useful as the variable isn't actually used for anything after the increment.

The problem s when u call each tym your function count is initialized so ultimately it will be 0 at the last tym it called.So better solution is have count as global var.For Eg

int count1=0;

int getUpper ( const string& s, int high) {

int count=0; if(s.size()>0) {

     if (s[0] <='Z' && s[0] >='A')
      count++;
     count1++;

   return getUpper(s.substr(1,s.size()-1), high-1);

}
 return count1;

}

Now count1 will give the result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM