HomeC ProgrammingC program to Check Whether a Number is Positive or Negative

C program to Check Whether a Number is Positive or Negative

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.

Share:

Leave a Reply

You May Also Like

This C program calculates the volume and surface area of a sphere using its radius. A sphere is a three-dimensional...
This C program converts a Roman numeral to a decimal number. Roman numerals are a system of numerical notation used...
This C program calculates the value of sin(x) using the Taylor series expansion. The Taylor series expansion is a mathematical...