Write a C program to enter any number 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, Switch case
Logic to check even or odd number using switch case
To get the logic of this program, you must know the concept of checking divisibility in C. If not learn it first.
Below is the step by step descriptive logic to check even or odd using switch case.
- Read a number from user, store it in some variable say num.
- Switch the even number checking expression. Which is switch (num % 2). The expression num % 2 will return either 0 or 1. 0 means num%2 => 0, it is even. 1 means num%2 => 1, the number is odd.
- For case 0, print even number.
- For case 1, print odd number.
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; /* * Read 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; }
Note: In no situation, the expression num % 2 will return other than 0 and 1. Hence, no other cases or default statement is required.
Learn other methods to code this program.
- Program to check even odd using if else.
- Program to check even odd using conditional operator.
- Program to check even odd using functions.
Output
Enter any number to check even or odd: 6 Number is Even
Happy coding ;)
You may also like
- Switch programming exercises index.
- C program to print day of week using switch case.
- C program to create simple Calculator using switch case.
- C program to check vowel or consonant using switch case.
- C program to find maximum between two numbers using switch case.
- C program to print total number of days in a month using switch case.