Given an array of integers, print to the console the positive numbers, one on each line.
A number n
is positive if it is strictly greater than 0
.
Example:
Input: nums = [3, -2, 0, 4, -4]
Output (console):
3
4
Note:
You have to print the numbers to the console, your function shouldn't return anything.
The core challenge of this problem is to iterate through the array and identify numbers that are strictly greater than zero. This is a common task in data filtering where we need to extract specific elements based on a condition.
Potential pitfalls include misunderstanding the condition for positivity (it must be strictly greater than zero, not equal to or greater than zero) and handling edge cases like an empty array or an array with no positive numbers.
To solve this problem, we can use a simple loop to iterate through the array and check each element. If an element is positive, we print it to the console. This approach is straightforward and efficient for this problem.
The naive solution involves iterating through the array and checking each element. This is actually optimal for this problem since we need to examine each element at least once.
Given the simplicity of the problem, the naive solution is already optimal. We can, however, ensure our implementation is clean and efficient.
#include <iostream>
#include <vector>
void printPositiveNumbers(const std::vector<int>& nums) {
// Iterate through each number in the array
for (int num : nums) {
// Check if the number is positive
if (num > 0) {
// Print the positive number
std::cout << num << std::endl;
}
}
}
int main() {
// Example usage
std::vector<int> nums = {3, -2, 0, 4, -4};
printPositiveNumbers(nums);
return 0;
}
The time complexity of this approach is O(n), where n is the number of elements in the array. This is because we need to check each element once. The space complexity is O(1) as we are not using any extra space that scales with the input size.
Consider the following edge cases:
To test the solution comprehensively, consider the following test cases:
[]
[-1, -2, -3]
[1, 2, 3]
[3, -2, 0, 4, -4]
When approaching such problems, it's important to:
In this blog post, we discussed how to print positive numbers from an array in C++. We covered the problem definition, approach, algorithm, code implementation, complexity analysis, edge cases, and testing. Understanding and solving such problems is crucial for developing strong problem-solving skills in programming.
For further reading and practice, consider the following resources: