Introduction
In this blog post, we will discuss how to check whether a given number is positive or negative in the C programming language. This is a common task in programming, and it can be easily accomplished using conditional statements.
Code Implementation
Let’s start by writing a simple C program to check whether a number is positive or negative. Here’s the code:
#include<stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if(num > 0) {
printf("The number is Positive");
}
else if(num < 0) {
printf("The number is Negative");
}
else {
printf("The number is Zero");
}
return 0;
}
This code prompts the user to enter a number, and then uses an if-else statement to check whether the number is positive, negative, or zero. The result is printed accordingly.
Explanation
The program starts by declaring an integer variable ‘num’ to store the user input. It then prompts the user to enter a number using the ‘printf’ and ‘scanf’ functions.
The if-else statement is used to check the value of ‘num’. If ‘num’ is greater than 0, it means the number is positive and the corresponding message is printed. If ‘num’ is less than 0, it means the number is negative and the corresponding message is printed. If ‘num’ is equal to 0, it means the number is zero and the corresponding message is printed.
Conclusion
Checking whether a number is positive or negative is a simple task in C programming. By using conditional statements, we can easily determine the sign of a given number. This can be useful in various applications where we need to differentiate between positive and negative numbers.