Positive, Negative, or Zero: Number Sign Program in 4 Languages
Check if a number is positive, negative, or zero in C, C++, Java, and Python. Covers the three-branch algorithm, ternary operators, and integer overflow edge cases.
Checking whether a number is positive, negative, or zero is one of the first control-flow problems placement tests include, and the most common implementation mistake is using only two branches.
The original algorithm many students learn goes: if the number is greater than zero, print Positive; otherwise, print Negative. That works for 56 (Positive) and for -56 (Negative). It fails for 0, which the else-case misclassifies as Negative. Zero is neither positive nor negative. A correct program always has three branches.
The Three-Branch Rule
The algorithm is simple once stated completely:
- If
num > 0, the number is positive. - If
num < 0, the number is negative. - If
num == 0, the number is zero.
That third branch is the one the two-branch version omits. Adding an else if (num < 0) before the final else prevents zero from falling through incorrectly. This is the same principle that applies to replacing zeros with ones in an integer: zero is always a distinct case, never safely bundled with the negative branch.
Implementation in C
The standard if-else approach:
#include <stdio.h>
int main() {
int num;
scanf("%d", &num);
if (num > 0)
printf("Positive\n");
else if (num < 0)
printf("Negative\n");
else
printf("Zero\n");
return 0;
}
The same logic using the ternary operator:
#include <stdio.h>
int main() {
int num;
scanf("%d", &num);
printf("%s\n", (num > 0) ? "Positive" : (num < 0) ? "Negative" : "Zero");
return 0;
}
Both produce identical output. The ternary version is concise but harder to read at a glance; the if-else form is preferred when code readability matters in reviews. Most interviewers who ask for a ternary version are checking that you know the nested form, not that you prefer it.
The Same Logic in Python, Java, and C++
The comparison operators and branch structure are identical across all four languages. What changes is syntax.
Python:
num = int(input())
if num > 0:
print("Positive")
elif num < 0:
print("Negative")
else:
print("Zero")
Java:
import java.util.Scanner;
public class SignCheck {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
if (num > 0)
System.out.println("Positive");
else if (num < 0)
System.out.println("Negative");
else
System.out.println("Zero");
}
}
C++:
#include <iostream>
using namespace std;
int main() {
int num;
cin >> num;
if (num > 0)
cout << "Positive" << endl;
else if (num < 0)
cout << "Negative" << endl;
else
cout << "Zero" << endl;
return 0;
}
A quick reference on syntax differences:
| Language | Branch keyword | Input method | Notes |
|---|---|---|---|
| C | else if | scanf | Needs stdio.h |
| C++ | else if | cin >> | Needs iostream |
| Java | else if | Scanner.nextInt() | Needs import |
| Python | elif | int(input()) | No imports needed |
Python does not support nested ternaries cleanly for three-way decisions. Avoid "Positive" if num > 0 else "Negative" if num < 0 else "Zero" in Python, valid but inverting the natural reading order. The if/elif/else form is the idiomatic Python choice.
Edge Cases: Zero, Integer Limits, and Floating-Point
The three-branch algorithm handles these edge cases correctly, but it is worth understanding why.
Zero
Input of 0 satisfies neither num > 0 nor num < 0, so the final else branch captures it and prints Zero. The original two-branch algorithm instead printed Negative for zero. That misclassification is a common reason this problem appears in placement tests: the examiner wants to see whether you think about boundary conditions.
Integer Boundaries
The C and C++ int type has fixed boundaries defined in <limits.h>. Per cppreference.com, these are:
INT_MAX— the largest signed int value, which is 2,147,483,647INT_MIN— the smallest signed int value, which is -2,147,483,648
Both are valid inputs. INT_MAX is positive and INT_MIN is negative. The comparison operators handle both without any special casing. If your input might exceed these bounds, switch to long long in C/C++ or long in Java. Python’s integers have arbitrary precision with no upper or lower bound, so no type change is needed there.
Floating-Point Inputs
If the input is a float or double, change the type and format specifier but keep the same three-branch logic. One edge case worth knowing: the IEEE 754 standard includes a negative zero (-0.0). In C, the comparison -0.0 < 0 evaluates to false, and -0.0 == 0 evaluates to true, so negative zero correctly prints Zero, not Negative.
The space complexity of any version of this program is O(1): one variable, no auxiliary storage, constant space regardless of input magnitude.
Where Sign Detection Appears in Larger Problems
The positive/negative/zero check looks trivial in isolation. It appears as a building block inside a surprising number of bigger problems.
Sorting algorithms use it continuously. Bubble sort compares two elements and decides whether to swap based on whether their difference is positive or negative. The sign of a - b is the entire decision. Profit and loss calculations reduce to the same logic: if revenue minus cost is positive, it is a profit; if negative, a loss; if zero, breakeven.
In digit-sum programs and similar number-processing problems, you often need to strip a negative sign before processing each digit. Sign detection becomes a preprocessing step before the main algorithm starts.
Binary search also reduces to this at its core: the midpoint comparison returns a positive difference (search right), a negative difference (search left), or zero (found). The implementation varies by language, but the three-case logic is identical.
In AI and machine learning systems, the pattern looks slightly different but works the same way: a model produces a score, and a threshold comparison decides the outcome. If the sentiment score is above zero, the text is positive; below zero, negative. If the confidence score exceeds a threshold, the prediction is accepted; otherwise, it is rejected or flagged for review. The comparison logic is identical to what you wrote above. Only the data changes.
That connection between basic sign detection and model output filtering is direct. TinkerLLM is where you can run real LLM API calls and build a small classifier that applies conditional logic to model outputs: the same if score > threshold pattern from this article, applied to live language model responses, for ₹299.
Primary sources
Frequently asked questions
What happens when the input is zero: is it positive or negative?
Zero is neither positive nor negative. A correct implementation needs three branches: greater than zero (Positive), less than zero (Negative), and equal to zero (Zero). The two-branch algorithm that treats zero as the else-case misclassifies it as Negative.
Can I use a ternary operator instead of if-else for this problem?
Yes. C, C++, and Java support nested ternaries: (num > 0) ? Positive : (num < 0) ? Negative : Zero. Python does not support nested ternaries cleanly for three-way comparisons; prefer the if/elif/else form in Python.
Does the program work for floating-point numbers?
The same three-branch logic works for float and double inputs. One caveat: IEEE 754 negative zero (-0.0) compares equal to positive zero (0.0), so the zero branch handles it correctly and prints Zero, which is the expected answer.
What is the space complexity of this program?
O(1). The program stores only the input number in a single variable. No auxiliary data structures are used, and storage does not grow with the magnitude of the input.
What input type should I use if the number can be very large?
For integers beyond INT_MAX or below INT_MIN, switch from int to long long in C or C++, or long in Java. Python integers have arbitrary precision by default, so no type change is needed in Python.
A self-paced playground for building with LLMs.
TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.
Try TinkerLLM (₹299 launch)