recursive problem

1
2
3
4
5
6
7
8
9
10
int sub(string &temp,int begin,int end){
	
	if(end-begin == 0){
	
		return temp[begin];
	}else{
	
	return sub(temp,begin+1,end) + temp[begin];}

}


i want to add all subset elements

but when i do

cout << sub(5) << endl;

it print 150.... wtf
cout << sub(5) << endl;

Shouldn't compile unless you have another overloaded version of sub.
yea i know... i just minimize the cout
string x = "123";
cout << sub(x,0,x.size()-1)<<endl;
if you want
150 is the correct output for:

1
2
string x = "123";
cout << sub(x,0,x.size()-1)<<endl;


Perhaps you wanted it to calculate 1 + 2 + 3 rather than '1' + '2' + '3' ?
oh ok

so how do u write for the
return sub(temp,begin+1,end) + temp[begin]

part?
i tried int and * but not sure
You can convert a single character that is also a digit to it's numerical value by subtracting '0' from the character.

1
2
3
4
5
6
7
8
9
int sub(string &temp,int begin,int end)
{
    int value = temp[begin] - '0' ;

    if ( end == begin )
        return value ;

    return sub(temp, begin+1, end) + value ;	
}
that is really helpful

thak you cire
1
2
3
4
int sub( const std::string &s, std::string::size_type pos, std::string::size_type n )
{
   return ( n == 0 ? 0 : s[pos] - '0' + sub( s, pos + 1, n - 1 ) );
}
Topic archived. No new replies allowed.