I'm trying to create a code that counts the number of positive and negative numbers from a given array using a function. For example in the array {-1, 2, -3, 4.5 , 0, .3, -999.99} it's supposed to show 2 positive numbers, and 4 negative numbers and excludes the number 0.
I'm using two counters to keep track of how many negative and positive numbers, a for loop to cycle through the array, but I don't know how to incorporate the boolean parameter when true or false is called on to display the right counter.
My code isn't outputting the right information and any tips would be help on how to improve my code.
#include <iostream>
using namespace std;
int countingArray(float list[], int size, bool)
{
int NumberOfPositives = 0;
int NumberOfNegatives = 0;
for (int index = 0; index < size; index++) {
if (list[index] > 0) {
if (true) {
NumberOfPositives++;
}
}
else if (list[index] < 0) {
if (false) {
NumberOfNegatives++;
}
}
else if (list[index] == 0)
continue;
}
return NumberOfPositives;
return NumberOfNegatives;
}
int main()
{
float list[] = { -1, 2, -3, 4.5, 0, -3, -999.99 };
cout << "# of Pos. = " << countingArray(list, 7, true) << endl;
cout << "# of Pos. = " << countingArray(list, 7, false) << endl;
system("PAUSE");
return 0;
}
You cannot return 2 values. Once you return, that function immediately ends.
Therefore, countingArray will only return the number of positive numbers you have, as return NumberOfPositives occurs before return NumberOfNegatives.
I would have wrote it this way:
void countingArray(float list[], int size, int& positive, int& negative) {
for (int index = 0; index < size; index++)
if (list[index] > 0)
++positive;
else if (list[index] < 0)
++negative;
}
int main() {
float list[] = { -1, 2, -3, 4.5, 0, -3, -999.99 };
int positive = 0;
int negative = 0;
countingArray(list, 7, positive, negative);
cout << "# of Pos. = " << positive << endl;
cout << "# of Pos. = " << negative << endl;
system("PAUSE");
return 0;
}
Pass the counters by reference so you don't loop array twice. And your problem is you return twice from your function if doing it your way you need to check the boolean flag before returning and return positive or negative counter based on your flag.
Also, you can use std::array instead c type array, that way you can loop through array using iterator and you won't need to pass array size.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With