Finding (positive - negative - odd - even - zero) numbers in an array
Take 20 integer inputs from the user and output the count of the following:
1. Positive numbers.
2. Negative numbers.
3. Odd numbers.
4. Even numbers.
5. Zeros.
Step 1: Declare a 20-element one-dimensional array.
int array[20];
Step 2: Prompt the user to enter 20 integer values and store them in the previously declared array - use a (for) loop to pass through the array indexes.
std::cout << "Enter twenty integers:\n";
for (int i = 0; i < 20; i++)
{
std::cout << "Integer #" << i + 1 << ": ";
std::cin >> array[i];
}
Step 3: Declare five integer variables that each of them stores the count of a specified type: (positive - negative - odd - even - zeros) and initialize each of them with values of zeros.
Note: Initially, the count of (positive) numbers is zero, so we put the initial value as zero. If we just write the declaration without giving an initial value, then we would find a random value when we output the final result.
int countPositive(0), countNegative(0), countOdd(0),
countEven(0), countZero(0);
for (int i = 0; i < 20; i++) { if (array[i] >= 0) countPositive++; else countNegative++;
if (array[i] % 2 != 0) countOdd++; else countEven++;
if (array[i] == 0) countZero++; }
std::cout << "\nPositive numbers: " << countPositive << '\n'; std::cout << "Negative numbers: " << countNegative << '\n'; std::cout << "Even numbers: " << countEven << '\n'; std::cout << "Odd numbers: " << countOdd << '\n'; std::cout << "Zeros: " << countZero << "\n\n";
Putting it all together:
#include <iostream>
int main()
{
int array[20];
std::cout << "Enter twenty integers:\n";
for (int i = 0; i < 20; i++)
{
std::cout << "Integer #" << i + 1 << ": ";
std::cin >> array[i];
}
int countPositive(0), countNegative(0), countOdd(0),
countEven(0), countZero(0);
for (int i = 0; i < 20; i++)
{
if (array[i] >= 0)
countPositive++;
else
countNegative++;
if (array[i] % 2 != 0)
countOdd++;
else
countEven++;
if (array[i] == 0)
countZero++;
}
std::cout << "\nPositive numbers: " << countPositive << '\n';
std::cout << "Negative numbers: " << countNegative << '\n';
std::cout << "Even numbers: " << countEven << '\n';
std::cout << "Odd numbers: " << countOdd << '\n';
std::cout << "Zeros: " << countZero << "\n\n";
system("pause");
return 0;
}
Comments
Post a Comment