C Program to check Even or Odd number using Switch Case
Even or Odd Number using Switch Case Program Description:
In earlier programs, we discussed the Even or Odd number program using the if else statement. In today’s article, We are going to write a C program to check Even or Odd number using Switch case or switch statement.
The program should take a positive number from the user and display if the given number is Odd or Even. If the user enters a Negative number, Program should display an Error message.
Expected Input and Output:
Example 1:
Input:
Enter a Positive Number: 10
Output:
10 is Even
Related Programs:
Pre-Requisite:
We are going to use the switch statement in the program, So please learn more about the switch statement with examples in the following article.
Even or Odd Number using Switch Case Program Algorithm:
- Program prompt for the user input. The user needs to provide a number. we are storing user input in a variable n.
- Now, We are going to use the switch case to check whether the number is an Even number or Odd number.
- We use the switch (n >= 0) condition.
- If this condition is
True, Then the
n is
Positive
- Now the switch (n >= 0) condition is True( i.e 1), So the given number n is either Positve number
- We are going to use another switch statement to detect if the number is and Even or Odd number. We can also use the If else statement here, But we are going to use the Switch statement.
- Let’s use the switch statement with n%2 == 0 condition, If this condition returns True (i.e 1), Then the given number n is an Even Number
- If n%2 == 0 condition is False( ), Then the n is Odd Number.
- If the switch (n >= 0) condition is False i.e ( ), Then n is Negative number. Display error message – Error: Please enter Positive Number
Program to Even or Odd Number using Switch Case:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
/* Program: C Program to check Even or Odd Number using Switch Case */ #include<stdio.h> int main() { // Request User Input int n; printf("Enter a Positive Number: "); scanf("%d", &n); // Let's us the switch case to find the odd or even // First check if the number 'n' is positive switch (n >= 0) { case 1: // 'n' is positive // Let's check if 'n' is Even or Odd Number switch (n%2 == 0) { case 1: // 'n' is Even printf("%d is Even \n", n); break; // We can also use 'default' here. case 0: printf("%d is Odd \n", n); break; } break; default: // 'n' is Negative printf("Error: Please enter Positive Number\n"); break; } return 0; } |
Program Output:
We are using the gcc compiler to compile and run the program.
gcc even-odd-switch.c
Run the program
1 2 3 4 5 6 7 8 |
$ ./a.out Enter a Positive Number: 10 10 is Even $ $ ./a.out Enter a Positive Number: 7 7 is Odd $ |
Invalid Input Case: If the user enters Invalid Input.
1 2 3 |
$ ./a.out Enter a Positive Number: -1 Error: Please enter Positive Number |