C Program to check Even or Odd number using Switch Case

C-Program-to-find-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:

  1. Program prompt for the user input. The user needs to provide a number. we are storing user input in a variable n.
  2. Now, We are going to use the switch case to check whether the number is an Even number or Odd number.
  3. We use the switch (n >= 0) condition.
  4. 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.
  5. 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:

Program Output:

We are using the gcc compiler to compile and run the program.

gcc even-odd-switch.c

Run the program

Invalid Input Case: If the user enters Invalid Input.

Venkatesh

Hi Guys, I am Venkatesh. I am a programmer and an Open Source enthusiast. I write about programming and technology on this blog.

You may also like...

Leave a Reply