Switch case Exercises
C program to check even or odd number using switch case
Write a C program to input number from user and check whether the number is even or odd using switch case. How to check even or odd using switch case in C programming. Logic to check whether a number is even or odd using switch case in C program.
Example
Input
Input number: 12
Output
Even number
Required knowledge
Basic C programming, Arithmetic operators, Switch case statement
Logic to check even or odd number using switch...case
A number is said even number if it is exactly divisible by 2. In C programming we use Modulo operator % to test divisibility of a number. The expression (num % 2) evaluates to 0 if num is even otherwise evaluates to 1.
In previous program we learned to write expressions inside switch case. The expression (num % 2) is used to test even numbers and can have two possible values 0 and 1 i.e. two cases.
Step by step descriptive logic to check even or odd using switch case.
1.Input number from user. Store it in some variable say num.
2.Switch the even number checking expression i.e. switch(num % 2).
3.The expression (num % 2) can have two possible values 0 and 1. Hence write two cases case 0 and case 1.
4.For case 0 i.e. the even case print "Even number".
5.For case 1 i.e. the odd case print "Odd number".
Important note: Since there are only two possible cases for the expression (num % 2). Therefore, there is no need for default case.
Program to check even or odd using switch...case
/** * C program to check Even or Odd number using switch case */ #include <stdio.h> int main() { int num; /* Input a number from user */ printf("Enter any number to check even or odd: "); scanf("%d", &num); switch(num % 2) { /* If n%2 == 0 */ case 0: printf("Number is Even"); break; /* Else if n%2 == 1 */ case 1: printf("Number is Odd"); break; } return 0; }
Output
Enter any number to check even or odd: 6
Number is Even