Home > Enterprise >  code is Not returning the correct character in cpp
code is Not returning the correct character in cpp

Time:03-19

Question: First uppercase letter in a string ( Recursive) Doubt: why this code is not returning the correct character even though it is entering in the if clause at correct time(when the letter is in uppercase). I have added these cout statements for debuging purpose only.

# include <bits/stdc  .h>
using namespace std;
char UpperCase(string str, int i){
    
    cout<<" str "<<i<<" "<<str[i]<<endl;
    if(i==str.length()){
        return '0';
    }
    if(str[i]>=65 && str[i]<=90 ){
        char r=str[i];
        cout<<" r "<<i<<" "<<r<<endl;
        return r;
    }
    
    UpperCase(str, i 1);
}
int main(){
string str;
char r;
cout<<"Enter string : ";
cin>>str;
 r=UpperCase(str,0);
 cout<<r<<endl;
 return 0;
}

output

Enter no of element : geeksforgeeKs
 str 0 g
 str 1 e
 str 2 e
 str 3 k
 str 4 s
 str 5 f
 str 6 o
 str 7 r
 str 8 g
 str 9 e
 str 10 e
 str 11 K
 r 11 K
ö

Expected

K (instead of ö)

CodePudding user response:

I'm assuming this is an academic exercise. No one would actually implement this task using recursion (nor would they use magic numbers, the plague known as <bits/stdc .h>, a dreadful practice common on junk "competitive" programming sites, etc.)

That said, a very common mistake made by students when learning recursion is failing to realize that function conveying their results by return-value need to be reaped from the recursed call. You've fallen victim to that mistake here.

Stripping the debugging statements and just looking at the code itself:

char UpperCase(string str, int i)
{
    if (i == str.length())
    {
        return '0';
    }
    if (str[i] >= 65 && str[i] <= 90)
    {
        return str[i];
    }

    UpperCase(str, i   1); // <===== HERE
}

Note that UpperCase returns a char (or at least it claims to). But in the recursed case you're not reaping that result. In fact, you're not returning anything . This is not only a logical bug, it also leads to undefined behavior. Anyone that invokes this function to reap its result and does not fall into one of the other two targeted exit conditions immediately will have no specified result. Your compiler will tell you this if you pay attention to its warnings:

warning: control reaches end of non-void function [-Wreturn-type]

The simplest way to address this is to remember what your function is supposed to return, and then make sure it returns it.

char UpperCase(string str, int i)
{
    if (i == str.length())
    {
        return '0';
    }
    if (str[i] >= 65 && str[i] <= 90)
    {
        return str[i];
    }

    return UpperCase(str, i   1); // <===== FIXED
}
  • Related