Reputation: 342
My homework assignment requires me to go through an array of doubles and return true or false depending on whether or not it contains a negative number or not. The catch is that I have to use a recursive function and I can't use loops. I also can't use access any functions or variables outside of the function I am given.
The function takes two parameters: the array, and the number of elements to be inspected.
I'm having trouble making it stop recursing once it has inspected the specified number of elements.
//what I have so far
bool anyNegative(const double a[], int n)
{
if(n <= 0)
return false;
if(*a < 0)
return true;
anyNegative(a + 1, n);
}
First, I thought of using counter, but that doesn't work since it gets reset every time the function recurses.
I also tried to compare pointer indexes with
if(currentElement == &a[n])
where currentElement is a pointer to the first element of array a.
However, I THINK the reason my program didn't work when I did that is because "a" is set to a new value every time the function is recursed so that &a[n] will always be n elements ahead of currentElement.
I'm stuck and if someone could give me a hint, that would be great.
Upvotes: 1
Views: 1081
Reputation: 311068
Size of an array can not be negative. So that do not do such a superfluous check as
if(n <= 0)
return false;
it is better to define the second parameter as having type size_t.
Your function has undefined behaviour because it returns nothing when the control will achieve statement
anyNegative(a + 1, n);
and moreover instead of the call above must be
anyNegative(a + 1, n -1);
I would write the function the following way
bool anyNegative( const double a[], size_t n )
{
if ( n == 0 ) return false;
return ( *a < 0 ? true : anyNegative( a + 1, n - 1 ) );
}
Upvotes: 0
Reputation: 233
You are missing two things, first you are not decrementing value of n
so that terminating condition can be reached. Secondly you are not returning the result of sub-executions to the upper level.
Here is the modified code:
//what I have so far
bool anyNegative(const double a[], int n)
{
if(n <= 0)
return false;
if(*a < 0)
return true;
return anyNegative(a + 1, n - 1);
}
Upvotes: 1
Reputation: 16178
You need to decrease n
, and also return the value of recursive call.
return anyNegative(a + 1, n - 1);
Upvotes: 1
Reputation: 170193
Decrease n
, since the array you pass is smaller
anyNegative(a + 1, n - 1);
Upvotes: 1