Recursive Programing Help Please

New poster to these forums and I'm a bit stuck on this one problem I have for my CIS class. My code for this problem is probably pretty bad at the moment as Im not sure how to proceed from here. C++ is still fairly new to me so if you could help that would be appreciated thanks.

Problem:
Write a recursive C++ function which accepts two parameters .. one int parameter, a value, and another int parameter, a digit and prints the number of times the digit occurs in the value. Write a short C++ main which reads in int value and calls this function.

You are not to use any global variables or add any other parameters to this function.


What I have so far:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
using namespace std;

int recursion(int value, int digit);

int main(){
	int value;
	int digit;
	
	cout << "Enter a number: ";
	cin >> value;

	cout << endl << "Enter a 1 digit number: ";
	cin >> digit;

	cout << endl << "Your 1 digit number occured " << recursion(value, digit) << " time(s) in the number you entered." << endl;

	return 0;
}

int recursion(int value, int digit){
	if( value % 10 == digit )
		return 1 + recursion(value/10 , digit);
	if( value <= 10){
		if (value == 6){
			return 1;
		}else 
			return 0;
	}
}
1
2
3
4
5
6
7
8
9
10
11
if ( value is greater than 10 )
{
     if ( last digit of value is equal to digit )
          return 1 + recursion(value/10, digit)
     else
          return recursion(value/10, digit)
}
else if ( value is equal to digit )
     return 1
else
     return 0



You're not too far off. It pays to think out the reasoning before you start writing the code.
Thanks for your help. Makes sense to me now.
Topic archived. No new replies allowed.