Count Positive and Negative Numbers

Count Positive and Negative Numbers

Easy C++ Arrays 30 views
Explanation Complexity

Problem Statement

Given an array with positive and negative numbers, count how many are positive and how many are negative. This builds conditional logic skills.
Logic: Check each number's sign and increment respective counter

Input Format

An integer n (size of array)
Then n integers (can be positive or negative).

Output Format

Two integers:

• count of positive numbers

• count of negative numbers

Example

6
-2 5 0 -7 3 9
Positive = 3
Negative = 2

Constraints

n ≥ 1

Zero is neither positive nor negative

Concept Explanation

Each element of the array is checked.
If the value is greater than 0, it is positive.
If the value is less than 0, it is negative

Step-by-Step Explanation

1.Read array size n.

2.Initialize two counters:

• posCount = 0

• negCount = 0

3.Traverse the array from index 0 to n-1.

4.For each element:

• If value > 0 → increment posCount.

• Else if value < 0 → increment negCount.

5.Ignore value 0.

6.Print posCount and negCount.

Concept Explanation

Each element of the array is checked.
If the value is greater than 0, it is positive.
If the value is less than 0, it is negative

Step-by-Step Explanation

1.Read array size n.

2.Initialize two counters:

• posCount = 0

• negCount = 0

3.Traverse the array from index 0 to n-1.

4.For each element:

• If value > 0 → increment posCount.

• Else if value < 0 → increment negCount.

5.Ignore value 0.

6.Print posCount and negCount.

Input / Output Format

Input Format
An integer n (size of array)
Then n integers (can be positive or negative).
Output Format
Two integers:

• count of positive numbers

• count of negative numbers
Constraints
n ≥ 1

Zero is neither positive nor negative

Examples

Input:
6 -2 5 0 -7 3 9
Output:
Positive = 3 Negative = 2

Example Solution (Public)

C++
void question4_count_pos_neg() {
    int arr[] = {5, -3, 8, -1, 0, -7, 12};
    int size = 7;
    int positive = 0, negative = 0;
    
    for(int i = 0; i < size; i++) {
        if(arr[i] > 0) {
            positive++;
        } else if(arr[i] < 0) {
            negative++;
        }
    }
    
    cout << "Positive: " << positive << ", Negative: " << negative << endl;
}

Official Solution Code

void question4_count_pos_neg() {
    int arr[] = {5, -3, 8, -1, 0, -7, 12};
    int size = 7;
    int positive = 0, negative = 0;
    
    for(int i = 0; i < size; i++) {
        if(arr[i] > 0) {
            positive++;
        } else if(arr[i] < 0) {
            negative++;
        }
    }
    
    cout << "Positive: " << positive << ", Negative: " << negative << endl;
}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.