Cover Image for C++ Program to Count Positive and Negative Numbers in an Array
95 views

C++ Program to Count Positive and Negative Numbers in an Array

You can create a C++ program to count positive and negative numbers in an array using a simple loop. Here’s an example program to do that:

C++
#include <iostream>

int main() {
    int n; // Size of the array
    int positiveCount = 0; // Count of positive numbers
    int negativeCount = 0; // Count of negative numbers

    // Input the size of the array
    std::cout << "Enter the size of the array: ";
    std::cin >> n;

    // Declare an array of size n
    int arr[n];

    // Input the elements of the array
    std::cout << "Enter the elements of the array:" << std::endl;
    for (int i = 0; i < n; i++) {
        std::cin >> arr[i];

        // Check if the element is positive or negative and update the counts
        if (arr[i] > 0) {
            positiveCount++;
        } else if (arr[i] < 0) {
            negativeCount++;
        }
    }

    // Display the counts
    std::cout << "Number of positive numbers: " << positiveCount << std::endl;
    std::cout << "Number of negative numbers: " << negativeCount << std::endl;

    return 0;
}

In this program:

  1. We first input the size of the array (n) and create an integer array arr of that size.
  2. We then input the elements of the array using a for loop.
  3. Inside the loop, we check each element of the array to determine if it’s positive (greater than 0) or negative (less than 0), and we update the respective counts accordingly.
  4. Finally, we display the counts of positive and negative numbers.

Compile and run this program, and it will count the positive and negative numbers in the array you provide as input.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS