C Program : Detect whether the entered number is even or odd

Determining Even or Odd: A C Program Using Nested Switch Statements

In the world of programming, making decisions based on conditions is fundamental. In this article, we'll explore a C program designed to detect whether a given number is even or odd. What sets this program apart is its use of nested switch() case statements, showcasing an interesting approach to conditional logic.

The Code:


 #include<stdio.h>
 main()
  {
    int x, y;
    printf("\n Enter a Number : ");
    scanf("%d", &x);
    switch( x )
     {
       case 0:
           printf("\n 0 is neither even nor odd");
           break;

       case 1:
           printf("\n 1 is odd");
           break;

       default:
           y = x % 2;
           switch(y)
              {
                 case 0:
                   printf("\n Number is Even : ");
                   break;

                 default:
                   printf("\n Number is Odd : ");
                   break;

              }


     }
  }

Explanation:

  1. User Input:

    The program begins by prompting the user to enter a number.

  2. Outer Switch Statement:

    The outer switch statement evaluates the entered number and handles specific cases:

    • If the number is 0, it prints that 0 is neither even nor odd.
    • If the number is 1, it declares that 1 is odd.
  3. Nested Switch Statement:

    If the entered number is neither 0 nor 1, the program calculates the remainder when dividing the number by 2 (y = x % 2). It then utilizes a nested switch statement to determine whether the calculated remainder is 0 (even) or not (odd).

Input and Output Example:

Assuming the user enters 5:

  • Input: Enter a Number: 5
  • Output: Number is Odd

This indicates that the program correctly identified the entered number, 5, as an odd number.

Conclusion:

Understanding conditional statements is crucial in programming, and this C program provides a unique glimpse into using nested switch() cases to determine whether a number is even or odd. Feel free to experiment with different input values to observe how the program handles various scenarios. Happy coding!

Post a Comment

0 Comments