Finding element recursively

I am trying to declare a function that find the fist occurence of negative element in double array.I am trying to do it such that the code finds the total number of non-negative elements that come before negative elements. If the function contains no negative number then return -1
1
2
3
4
5
6
7
8
9
10
11
12
13
int firstNegative(const double a[], int n)
	{
		if(n<=0) return -1;
		if(n==1)
		{
			if(*a>=0)return 1;
			return 0;
		}
		if(*a>=0) {
		return 1+ firstNegative(a+1,n-1);	
		}
			return 0;
}

Here I cant get the code to work. It will return the size of the array if there is no negative element.I can get it to work if I can somehow get the size of the array, but apparently sizeof(a);does not work (always return 4, which I think is the size of the pointer to double)Any help appreciated!

Also why a cannot be treated as a normal array? I mean I can treat an array as both pointer and array if I were to declare it locally.
What are you asking?
Last edited on
(1) Is there any way to get the function to return -1 if all elements in array are negative, since I cannot get the size of the array?
(2)Why operation such as sizeof(ARRAY) do not work in array passed from another function?
What is int n?
@1 Create a static bool. On the recursion, check every time if the numb is negative. If it is, the bool is true in this instance. When going to finish, check if the bool is true; case true, return -1.

@2 sizeof is a compile-time operator. Use an std::array<(size_you_want),(type_you_want)>, a std::vector<(data_type)> (resize-able array) or an std::map<(access_type),(data_type)>

http://www.cplusplus.com/reference/array/array/
http://www.cplusplus.com/reference/vector/vector/
http://www.cplusplus.com/reference/map/map/
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>
class NoNegativeNumber //Just for checking if didn't ecountered negative. You can change it later.
{
public:
	NoNegativeNumber()
	{
	};
};



int first_negative(const double a[], int n)
{
	if (n < 1) throw NoNegativeNumber();
	if (a[0] < 0) return 1;
	return 1 + first_negative(a+1, n-1);
}

int main()
{
	double test[7] = {1,2,3,4,5,-6,7};
	try
	{
		std::cout << first_negative(test, 7);
	}
	catch(NoNegativeNumber exception)
	{
		std::cout << "No negative number found";
	}
}
Topic archived. No new replies allowed.