C program to check even or odd number using switch case

Previous Program Next Program

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.

  1. Read a number from user, store it in some variable say num.
  2. 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.
  3. For case 0, print even number.
  4. 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.

Output
Enter any number to check even or odd: 6
Number is Even

Happy coding ;)

You may also like

Previous Program Next Program
Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< pre>< code >----Your Source Code---- < / code > < / pre > (Remove spaces from pre and code tags)

No comments:

Post a Comment