Check whether a Number is Positive or Negative in C

Exercise:

Write a C Program to check whether a number is positive or negative.

1. Check using If-else

Click Here to View the Solution!
#include <stdio.h>        
int main() {
    double number;
    printf("Enter a number: ");
    scanf("%lf", &number);
    if (number <= 0.0) {
        if (number == 0.0) {
            printf("You entered 0.");
        }
        else {
            printf("You entered a Negative Number.");
        }
    }
    else {
        printf("You entered a Positive Number.");
    }
    return 0;
}
Click Here to View the Output!
Enter a number: 5
You entered a Positive Number.

Click Here to View the Explanation!
  • This program is used to determine whether an entered number is positive or negative using if…else statement.
  • The program requests the user to enter a number and stores it in a double type variable number using the scanf() function.
  • Initially, the program checks whether number is less than or equal to zero and if true, prints the message : You entered a negative number.
  • If false, the else statement is executed that prints the message : You entered a positive number.
  • The return 0 statement is used to exit the program execution.

2. Check using nested If-else

Click Here to View the Solution!
#include <stdio.h>      
int main() {
    double number;
    printf("Enter a number: ");
    scanf("%lf", &number);
    if (number == 0.0) {
        printf("You entered 0.");
    }
    else if (number <0.0) {
        printf("You entered a Negative Number.");
    }
    else if (number> 0.0) {
        printf("You entered a Positive Number.");
    }
    return 0;
}
Click Here to View the Output!
Enter a number: 7
You entered a positive number. 
Click Here to View the Explanation!
  • This program is used to determine whether an entered number is positive or negative using nested if…else statement.
  • The program requests the user to enter a number and stores it in a double type variable number using the scanf() function.
  • In the if statement, the program checks whether number is less than 0 and if true, prints the message : You’ve entered a negative number.
  • If the if statement is false, the else if condition is checked which checks whether number is greater than 0 and if true, prints the message : You’ve entered a positive number.
  • If neither of the if and else if statements are true, the else statement is executed which prints the message : You ‘ve entered 0.
  • The return 0 statement is used to exit the program execution.
%d bloggers like this: