I was asked to create a function that checks if an array of double
s has all negative numbers or none. If these 2 (all negative, all positive) are false, check the first negative number, using recursion and only using built-in C++ features.
int first_negative(const double val [] , unsigned array, unsigned short instance_ = 0) //Dont change instance!
{
//None negative?
bool none_negative;
for(int i = 0; i < array; i++)
{
if(val[i] > 0) none_negative = true;
else
{
none_negative = false;
break;
}
}
if(none_negative) return 0;
//All negative?
bool negative_instance;
for(int i = 0; i < array; i++)
{
if(val[i] < 0) negative_instance = true;
else
{
negative_instance = false;
break;
}
}
//Never change instance!
static short instance = instance_;
if(array < 1) return 0;
if(val[instance] < 0) return instance;
instance++;
return first_negative(val, array, instance);
}
Can I make it better? Can I remove the instance
parameter?
none_negative == true
as assignment, when it is not... – Uri Agassi 4 hours ago