Quick links
Write a C program to input a number and check positive negative or zero using switch case. Checking negative, positive or zero using switch case is little tricky. In this example, I will explain how to check positive negative or zero using switch case. However, it is not recommended way, it’s just for learning.
Input
Input number: 23
Output
23 is positive
Required knowledge
Basic Input Output, Switch case
How to check positive negative or zero using switch case
We already know how to check whether a number is positive, negative or zero using if else if. However, checking using switch case if little tricky since, switch
works with constants.
Switch case expects an expression that must return a list of known constant. So first let us define expressions to check positive, negative or zero.
(num > 0)
return 1 (true
) for positive number, otherwise 0 (false
).
(num < 0)
check negative and return 1 for negative number, otherwise 0.
(num == 0)
return 1 for zero, otherwise 0.
Next, to code this we will require nested switch
. Step by step descriptive logic to check positive negative or zero using switch case.
- Input number from user, store it in some variable say num.
- First we will check for positive. Use expression to check positive in outer switch. Use
switch(num > 0)
. - The above switch expression with either return 1 or 0. Hence for
case 1:
print positive number. - For
case 0:
write one more nested switch statement with expression to check negative number. Sayswitch (num < 0)
. - For above switch expression the number can either be negative or zero. Since outer switch already says its not positive.
- Hence for
case 1:
print negative and forcase 0:
print zero.
Program to check positive negative or zero using switch case
/**
* C program to check positive negative or zero using switch case
*/
#include <stdio.h>
int main()
{
int num;
printf("Enter any number: ");
scanf("%d", &num);
switch (num > 0)
{
// Num is positive
case 1:
printf("%d is positive.", num);
break;
// Num is either negative or zero
case 0:
switch (num < 0)
{
case 1:
printf("%d is negative.", num);
break;
case 0:
printf("%d is zero.", num);
break;
}
break;
}
return 0;
}
Output
Enter any number: 23 23 is positive. Enter any number: -22 -22 is negative. Enter any number: 0 0 is zero.
Happy coding 😉
Recommended posts
- Switch case programming exercises index.
- How to print total number days using switch case.
- Program to check vowel or consonant using switch case.
- C program to find maximum or minimum using switch case.
- Program to find roots of a quadratic equation using switch case.
- Program to create simple calculator using switch case.