Write C Program to enter any number and check whether number is odd or even using Conditional/Ternary operator.

Write a C program to enter any number and check whether number is even or odd using Conditional/Ternary operator ( ?: ). How to check even or odd numbers using conditional operator in C program. Checking whether a given number is even or odd using ternary operator in C programming. 

Example:
Input number: 10
Output: Even number



Required knowledge

Basic C programming, Conditional operator 


Even numbers

Even numbers are the positive integers that are exactly divisible by 2. For example: First 5 even numbers are - 2, 4, 6, 8, 10... 


Odd numbers

Odd numbers are the positive integers that are not exactly divisible by 2. For example: First 5 odd numbers are - 1, 3, 5, 7, 9... 


Program to check even or odd

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
 * C program to check even or odd number using conditional operator
 */

#include <stdio.h>

int main()
{
    int num;

    /*
     * Reads a number from user
     */
    printf("Enter any number to check even or odd: ");
    scanf("%d", &num);

    /* if(n%2==0) then it is even */
    (num%2 == 0) ? printf("The number is EVEN") : printf("The number is ODD");

    return 0;
}

Note: We can also write same program using conditional operator as:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
 * C program to check even or odd number using conditional operator
 */

#include <stdio.h>

int main()
{
    int num;

    /*
     * Reads a number from user
     */
    printf("Enter any number to check even or odd: ");
    scanf("%d", &num);

    /* Print Even if (n%2==0) */
    printf("The number is %s", (n%2==0 ? "EVEN" : "ODD"));

    return 0;
}


Output
Enter any number to check even or odd: 20

The number is EVEN


Comments

Most Viewed

Write C program to enter any year and check whether year is leap year or not using conditional/ternary operator.

WAP to input week number and print week day name.

C Program to Find Third Angle of a Triangle