C program to check if a number is even or odd using ternary operator


Learn to efficiently determine even or odd numbers in C programming using the conditional operator. Explore concise methods for number classification and enhance your C coding skills with this tutorial.

In this article, we'll explore how to create a simple C program to check whether a number is even or odd using the conditional (ternary) operator.

Understanding Even and Odd Numbers

  • Even Numbers: Numbers divisible by 2 without leaving a remainder are considered even.
  • Odd Numbers: Numbers not divisible by 2 without leaving a remainder are classified as odd.

C program to check whether a number is even or odd using conditional operator

Let's delve into the C programming language to create a program that checks whether a number is even or odd using the conditional operator.

#include <stdio.h>

int main() {
    int number;

    // Input from the user
    printf("Enter a number: ");
    scanf("%d", &number);

    // Checking even or odd using conditional operator
    (number % 2 == 0) ? printf("%d is an even number.", number) : printf("%d is an odd number.", number);

    return 0;
}

Output

Enter a number: 4
4 is an even number.

Checking Even or Odd: The program uses the conditional operator to check if the number is divisible by 2 (even) or not. Based on the result, it displays whether the number is even or odd.

In this article, we've created a simple C program that efficiently determines whether a number is even or odd using the conditional operator. Utilizing the conditional operator in C programming enables us to streamline conditional checks and classify numbers as even or odd effectively.


Recommended Posts