I have the below start on an issue and am looking for some guidance if you please. I am attempting to count the number of negatives in an array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
template< typename T>
T countNegatives( T * a, int N, int count = 0 ) // a is the name of the array, N is the length of the array
{
if ( N == 1 )
{
return count;
}
if (a[N] > 0)
{
count++;
}
else
{
count ++;
return countNegatives(a+1, N-1);
return count;
} // (a+1, N-1) is the rest of the array
}
template< typename T>
T countNegatives( T * a, int N ) // a is the name of the array, N is the length of the array
{
T sum = 0;
for (int i = 0; i < N; i++)
{//open for loop
if (a[i] < 0){
sum ++;
}
else {
}
}//close for loop
return sum;
}
//- You can't return two values, Pass what you need by reference instead;
//- You are returning T, but I don't see how you actually do this in your function
//- You increment count regardless if if a[N] is positive or negative
//- You quit if N==1, but N doesn't that mean there is still one value left?
//- Check a[N], if the array is 13 long and you refer to a[13], you'll overflow the array.
1 2 3 4 5 6 7 8 9
template< typename T>
int countNegatives( T a[], int N, int &count = 0 ) // passing count by reference.
{
if ( N == 0 ) return count;
if (a[N-1] < 0) count++; // Checks if the last value is negative, if so, increment count
return countNegatives(a, N-1, count);
}