Check Positive Negative Zero
Given an integer, determine whether it is positive, negative, or zero. Return "positive" if the number is greater than 0, "negative" if it is less than 0, or "zero" if it equals 0.
For example, the number 5 returns "positive". The number -3 returns "negative". The number 0 returns "zero". This is a fundamental conditional logic problem that teaches the three-way comparison pattern used in sorting networks, signum functions, and comparison-based algorithms.
The solution uses a simple if-else-if chain: check if the number is greater than 0 (positive), then check if it is less than 0 (negative), otherwise it must be zero. The order of checks does not matter as long as all three cases are covered. Using an else clause for the zero case is clean and ensures exactly one branch executes.
This pattern of three-way comparison appears in many real-world applications: determining the sign of a bank balance, checking temperature relative to freezing, evaluating game scores, and categorizing sensor readings. Understanding conditional branching is a prerequisite for more complex decision-making logic in algorithms.
Edge cases include very large positive numbers, very large negative numbers, and integer overflow scenarios where the distinction between positive and negative is still preserved by the sign bit.
Example Input & Output
Because the value is exactly 0.
Because -3 is less than 0.
Because 8 is greater than 0.
Algorithm Flow
Solution Approach
Use an if-else-if chain to check whether the number is greater than 0, less than 0, or exactly 0.
First check if n > 0 — if true, output "positive". If not, check if n < 0 — if true, output "negative". If neither condition is true, the number must be 0, so output "zero". The order of the first two checks does not matter as long as all three cases are covered. The else clause ensures that exactly one output is produced for any integer input.
This three-way comparison is the simplest form of multi-branch conditional logic. It is equivalent to the signum function (sign function) in mathematics, which returns -1, 0, or 1 depending on the sign of the input. Time complexity is O(1) with a constant number of comparisons.
Best Answers
program check_positive_negative_zero
dictionary
n: integer
algorithm
input(n)
if n > 0 then
output("POSITIVE")
else
if n < 0 then
output("NEGATIVE")
else
output("ZERO")
endif
endif
endprogramComments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
