C Program to Check Positive or Negative Number
Determining whether a number is positive, negative, or zero is one of the most basic programs in C programming.
It helps beginners understand conditional statements like if, else if, and else.
1. Problem Statement
Write a C program to check whether a given number is positive, negative, or zero.
Input: -5 Output: Negative Number
2. Method: Using if-else
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (num > 0) {
printf("Positive Number");
} else if (num < 0) {
printf("Negative Number");
} else {
printf("Zero");
}
return 0;
}
This is the simplest and most commonly used approach.
3. Method: Using Ternary Operator
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
(num > 0) ? printf("Positive") : (num < 0) ? printf("Negative") : printf("Zero");
return 0;
}
This approach reduces code length but may be less readable for beginners.
4. Algorithm
1. Start
2. Input number
3. If number > 0 → Positive
4. Else if number < 0 → Negative
5. Else → Zero
6. End
5. Edge Cases
1. Input is 0
2. Large positive or negative values
3. Invalid input (non-integer)
6. Common Mistakes
1. Forgetting to handle zero
2. Using wrong comparison operators
3. Missing return statement
7. Applications
1. Input validation
2. Mathematical computations
3. Conditional decision making
Conclusion
Checking whether a number is positive or negative is a fundamental concept in programming.
It builds the foundation for understanding conditional logic in C.
Codecrown