MeetCode - Programming Platform | MeetCode - Programming Solutions Platform

C++ Program to Count Positive and Negative Numbers with Explanation

C++ Easy Arrays 31 views
This problem helps you practice core C++ fundamentals in a practical way. It builds intuition around positive, negative, count. Let’s break it down step by step so you can implement it confidently.
Back to Questions

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

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 Logic

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.

Code Solution

This explanation is written for learning purposes and to help beginners understand the concept clearly.
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; }

Output Example

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

Common Mistakes

- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).

Notes & Extra Practice

Solutions (0)

No solutions submitted yet. Be the first!

Prev Next