Number entered is positive, negative or zero using else-if ladder
C program to check whether a number is positive, negative or zero using else if ladder.
Program
#include<stdio.h>
#include<conio.h>
void main()
{
int num;
printf("Enter a number\t:");
scanf("%d",&num);
if(num == 0)
printf("Number entered is zero");
else if(num > 0)
printf("Number entered is positive");
else
printf("Number entered is negative");
getch();
}
Output
********** Run1 **********
Enter a number :12
Number entered is positive
********** Run2 **********
Enter a number :0
Number entered is zero
********** Run3 **********
Enter a number :-43
Number entered is negative
Explanation
A number is taken as an input from the user and stored in the variable named say 'num'.
To check whether the number entered is zero or not, condition
If false, then it is checked for positive using the condition
If this condition is also false, then it is neither zero nor a positive number. So, by default that number is negative. So, no need to check the condition and hence, else block is used.
To check whether the number entered is zero or not, condition
(num == 0)
is checked.
If false, then it is checked for positive using the condition
(num>0)
.
If this condition is also false, then it is neither zero nor a positive number. So, by default that number is negative. So, no need to check the condition and hence, else block is used.