## Need help: Using Recursion function to count a letter

Moderators: Darobat, RecursiveS, Dante Shamest, Bugdude, Wizard

I finally figured it out

Code: Select all
`#include<iostream.h> #include<string.h> int word(char*); void main() {    char w[30];    cout << "Please enter a word: ";    cin  >> w;    cout << endl <<"We have " << word(w) << " A's on this word" << endl << endl; } int word(char *x) {    int ctr = 0;    if( *x != '\0')   {      if( *x != 'a')       {          x++;         return word(x);       }       else       {             ctr++;               x++;         return ctr + word(x);             }    }   else   {      return 0;   }} `
jinx

Code: Select all
`int w(char *x){return *x?w(x+1)+(*x=='a'):0;}`

Alvaro
Moderator

Posts: 5185
Joined: Mon Sep 22, 2003 4:57 pm
Location: NY, USA

alvaro your code is very simple....i tried it and it works the same as my code. I have a question about the "?" on your code. What is that for? , i guess i havent learn that yet.
jinx

It's a shorthand if/else

Code: Select all
`if (a == 3){    b = 5;}else{    b = 10;}`

is written as
Code: Select all
`b = (a==3)? 5 : 10;`

IOW
comparison ? value if true : value if false;
There are only 10 types of people in the world -- those that use binary, and those that don't
WaltP

Posts: 1187
Joined: Thu Oct 16, 2003 11:24 am

The other tricky part in my function is that using as an integer, (*x=='a') will evaluate to 1 when it's true and to 0 when it's false.

Alvaro
Moderator

Posts: 5185
Joined: Mon Sep 22, 2003 4:57 pm
Location: NY, USA

Alvaro wrote:The other tricky part in my function is that using as an integer, (*x=='a') will evaluate to 1 when it's true and to 0 when it's false.

Tricky? Why give a noob a tricky answer that he can't understand, instead of a straight forward one he can?

Showoff
There are only 10 types of people in the world -- those that use binary, and those that don't
WaltP

Posts: 1187
Joined: Thu Oct 16, 2003 11:24 am

WaltP wrote:Why give a noob a tricky answer that he can't understand, instead of a straight forward one he can?

Ok, the non-tricky version of that function is this:
Code: Select all
`unsigned count_a(const char *s){   if(*s=='\0')      return 0;   if(*s=='a')      return 1+count_a(s+1);   else      return count_a(s+1);}`

Showoff

Just a little bit.

Alvaro
Moderator

Posts: 5185
Joined: Mon Sep 22, 2003 4:57 pm
Location: NY, USA

very nice....thanks guys
jinx

Previous