In programming, it is often necessary to check whether a number is positive or negative. In this program, we will write a C program that prompts the user to enter a number, checks whether the number is positive or negative, and prints the result.
Problem Statement
The problem statement is to write a C program that prompts the user to enter a number, checks whether the number is positive or negative, and prints the result.
Solution
Here is the C program to check whether a number is positive or negative:
#include <stdio.h> int main() { int num; printf("Enter a number: "); scanf("%d", &num); if (num > 0) { printf("%d is positive\n", num); } else if (num < 0) { printf("%d is negative\n", num); } else { printf("Number is zero\n"); } return 0; }
Output
Explanation
First, we include the stdio.h
header file which is used for input/output functions. Then, we define the main()
function as the starting point of our program.
We declare an integer variable num
which will be used to store the number entered by the user.
Next, we prompt the user to enter a number using the printf()
function. The scanf()
function is used to read in the number entered by the user. The first parameter to scanf()
is the format string “%d” which specifies that the input should be read in as an integer. The second parameter is the address of the num
variable where the input should be stored.
We then use an if-else statement to determine whether the number is positive, negative, or zero. If the number is greater than 0, we print that the number is positive using the printf()
function. If the number is less than 0, we print that the number is negative. If the number is 0, we print that the number is zero.
Finally, we return 0 to indicate that the program executed successfully.
Conclusion
In this tutorial, we learned how to write a C program to check whether a number is positive or negative. We used the scanf()
function to read in the number entered by the user, and we used an if-else statement to determine whether the number is positive, negative, or zero. We then printed the appropriate message using the printf()
function.