c++ - Recursive Function Scanning String to Add ASCII -
so i'm trying figure out how this:
write recursive function sum of char's within c string.
i'm little rusty in doing normally, got work normal loop:
int countstr(string s) { int sum = 0; if(s.length() == 0) { exit(0); } (unsigned int = 0; < s.size(); i++) { sum += s[i]; } return sum; }
i can go inside main , this:
int main () { cout << "this word adds " << countstr("hello") << " in ascii " << endl; }
and works should, counting , adding characters in string via ascii numbers. problem i'm having trying figure out how typed works recursively. know need forgo loop in lieu of calling function itself, don't know use instead of sum += s[i]; have going in loop. i've been looking around in c string library, don't see can replace [i] loop calls up. know should using this? i'm not looking answer in code, need in should using make happen.
this 1 of many ways it.
int reccountstr(string s, int i){ if(s.size() == i) return (0 + s[i]); else return reccountstr(s, + 1) + s[i]; }
and in main call 0 initial argument.
cout << "this word adds " << reccountstr("hello", 0) << " in ascii " << endl;
Comments
Post a Comment