You are currently viewing C Program To Check A Given Number Is A Positive Or Negative Number Using If-else

C Program To Check A Given Number Is A Positive Or Negative Number Using If-else

In this program, you will learn how to write a C program to check whether a given number is a positive number or a negative number. Let’s understand this problem with some examples and algorithms.

Problem Statement

Our problem statement is you have to write a C program that takes a number as input and checks whether it is positive or negative.

Below is an example for a better understanding.

Examples:

Enter a number: 5

Output: The number is positive.

Enter a number: -7

Output: The number is negative.

Algorithm

  1. Start the program.
  2. Declare a variable number of type int to store the input number.
  3. Print a message asking the user to enter a number.
  4. Read the input number using scanf and store it in the number variable.
  5. Use if-else statements to check the sign of the number:
    • If number is greater than 0, print “The number is positive.”
    • Else if number is less than 0, print “The number is negative.”
    • Else, print “The number is zero.”
  6. End the program.

Program to check whether a given number is a positive or negative number

#include <stdio.h>
int main() {
    int number;
    printf("Enter a number: ");
    scanf("%d", &number);
    if (number > 0) {
        printf("The number is positive.\n");
    }
    else if (number < 0) {
        printf("The number is negative.\n");
    }
    else {
        printf("The number is zero.\n");
    }
    return 0;
}

Output 1

Enter a number: 44
The number is positive

Output 2

Enter a number: -44
The number is negative

Program Explanation

  • The program starts by including the necessary header file stdio.h.
  • The main() function is defined.
  • Inside the main() function, a variable number of type int is declared to store the user’s input.
  • The program prompts the user to enter a number by printing the message “Enter a number: “.
  • The scanf() function is used to read an integer from the user, and the input is stored in the number variable using the & operator.
  • The program checks the sign of the number using if-else statements:
    • The first if statement checks if the number is greater than 0. If true, it prints “The number is positive.”
    • The else if statement checks if the number is less than 0. If true, it prints “The number is negative.”
    • If none of the above conditions are satisfied, the else statement executes and prints “The number is zero.”
  • The return 0 statement ends the program.

Conclusion

This C program allows the user to enter a number and determines whether it is positive, negative, or zero using if-else statements. It covers all possible cases and provides the appropriate output based on the input.