recursive array counter

closed account (zwA4jE8b)
I don't need help with the assignment, I am happy with it.
I am just wondering if there is a way to start at A[0] instead of A[l](l being the max position) without using variables or more parameters?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//Michael Ervin - CS3 - Assignment 2 - Recursive occurence counter - 8/24/2011 - 8:50pm

#include <iostream>

int occurences(int A[], int l, int t)
{
	if(l >= 0)
		if(A[l] == t)
			return 1 + occurences(A, l - 1, t);
		else
			return 0 + occurences(A, l - 1, t);
	return 0;
}

int main()
{
	int A[10] = {2, 5, 2, 6, 7, 8, 12, 2, 2, 0};
	std::cout << "The number 2 occurs " << occurences(A, 9, 2) << " times";
	std::cin.get();
	return 0;
}


i just can't come up with a method
Last edited on
A std::vector could do the trick if you're allowed to use it.
Since you have the length of the input, it can be done with the code you already have. You just need to move the pointer you pass to the function.
I thought of that as well, however I realized that you'd have to declare the size as a const somewhere and that would conflict with the requirement of "without using variables". Maybe if CreativeMFS isn't as strict in that regard?
closed account (zwA4jE8b)
thank you helios. I often forget simple things (array variable is a pointer to the base)

1
2
3
4
5
6
7
8
9
int occurences(int A[], int l, int t)
{
	if(l >= 0)
		if(*A == t)
			return 1 + occurences(++A, l - 1, t);
		else
			return 0 + occurences(++A, l - 1, t);
	return 0;
}
Topic archived. No new replies allowed.