A positive, negative, or zero number can be identified by comparing it with 0. This program uses conditional statements to determine the type of the given number.
- If the number is greater than 0, it is positive.
- If the number is less than 0, it is negative; otherwise, it is zero.
Examples
Input: 10
Output: Positive
Explanation: Since 10 is greater than 0, it is positive.Input: -5
Output: Negative
Explanation: Since -5 is less than 0, it is negative.
Ways to Check for Positive Numbers, Negative Numbers, or Zero
There are two ways to check whether a given number is positive, negative, or zero:
1. Using Conditional Statements Like if-else
The simplest way to check whether a number is positive, negative, or zero is by using an if-else-if ladder.
- First, check if the number is 0; then check if it is less than 0 (negative).
- If neither condition is true, the number is greater than 0 and is positive.
#include <stdio.h>
void checkNum(int N) {
// Check if the number is zero
if (N == 0) {
printf("Zeri\n");
}
// Check if the number is less than zero
else if (N < 0) {
printf("Negative\n");
}
// If neither, the number is positive
else {
printf("Positive\n");
}
}
int main() {
int N = 10;
checkNum(N);
return 0;
}
Output
Positive
2. Using Bitwise Operators
The most significant bit (MSB) of an integer represents its sign in a signed binary representation. A 0 sign bit indicates a positive number, while a 1 sign bit indicates a negative number.
- The MSB can be extracted using bitwise operators to determine whether the number is positive or negative.
- Zero must be checked separately because its sign bit alone cannot distinguish it from a positive number.
#include <stdio.h>
void checkNum(int N) {
// Check if the number is zero
if (N == 0) {
printf("Zero\n");
return;
}
// Extracting msb
int msb = N & (1 << (sizeof(int) * 8 - 1));
if (msb)
printf("Negative\n");
else
printf("Positive\n");
}
int main() {
int N = 10;
checkNum(N);
return 0;
}
Output
Positive