Recursion

Mar 7, 2012 at 9:28pm
a
Last edited on Mar 9, 2012 at 3:06am
Mar 7, 2012 at 9:40pm
a
Last edited on Mar 9, 2012 at 3:06am
Mar 7, 2012 at 9:43pm
Not exactly the same, but hope it helps.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

int count2s(const char *fb, int index = 0)
{
  static int count = 0; // static variable will exist the whole lifespan of program
  if(fb[index] == '2')
    ++count;
  if(index < 30)
    return count2s(fb,++index);
  return count;
}

int main()
{
  const char *foobar = "123456789198293849573918439282";
  std::cout << count2s(foobar) << std::endl;
  return 0;
}


Output is 4
Last edited on Mar 7, 2012 at 9:44pm
Mar 7, 2012 at 9:56pm
a
Last edited on Mar 9, 2012 at 3:06am
Mar 7, 2012 at 10:33pm
Im soooo close, can anyone help here?
Mar 7, 2012 at 11:39pm
countLargerThanValue returns a count. Why are you not using it?
Mar 8, 2012 at 2:42am
I'm not sure what you mean, I am returning the count on line 19.
Mar 8, 2012 at 3:06am
does anyone know what cire means, or what is keeping me from the solution?
Mar 8, 2012 at 3:18am
a
Last edited on Mar 9, 2012 at 3:06am
Mar 8, 2012 at 3:59am
I'm not sure what you mean, I am returning the count on line 19.


You are returning the local variable count. You are not doing anything with the value returned from countLargerThan.
Last edited on Mar 8, 2012 at 4:00am
Mar 8, 2012 at 1:21pm
a
Last edited on Mar 9, 2012 at 3:06am
Mar 8, 2012 at 2:43pm
How about:
1
2
3
4
5
6
7
8
template< typename T >	                    
int LinkedList<T>::countLargerThan(Node<T> * head, T  val, int count = 0)
{
    if (head && head->data > val)
      count++;
    return (head == NULL || head->next == NULL) ? count : countLargerThan(head->next,val,count++);
  }
}


Or without ternary operator
1
2
3
4
5
6
7
8
9
10
11
12
template< typename T >	                    
int LinkedList<T>::countLargerThan(Node<T> * head, T  val, int count = 0)
{
    if(head == NULL)
      return count;
    if (head->data > val)
      count++;
    if(head->next == NULL)
      return count;
    return countLargerThan(head->next,val,count++);
  }
}


EDIT: changed return type to int because in the case where LinkedList<std::string> would fail for implicit conversion from int
Last edited on Mar 8, 2012 at 2:47pm
Mar 8, 2012 at 2:52pm
Texan, great point adding count to the function def. Now if I could just figure out how to mark a forum question as solved!

Thanks again for everyone help w/ this query.
Topic archived. No new replies allowed.