C program to check if number is even or odd
Category: C Program
Write a program to check if a number is even or odd in different ways. Let us use the if-else, ternary operator and switch case to explore different ways to check if a given number is even or odd.
Let us use the if-else, ternary operator and switch case to explore different ways to check if a given number is even or odd.
Write a program to check if a number is even or odd using if-else
#include <stdio.h>
void main() {
int num;
printf("Enter number to check: ");
scanf("%d", &num);
if (num % 2 == 0)
printf("%d is even", num);
else
printf("%d is odd", num);
}
We can further simplify the code as follows -
if (!(num % 2))
printf("%d is even", num);
else
printf("%d is odd", num);
Write a program to check if a number is even or odd using the ternary operator
#include <stdio.h>
void main() {
int num;
printf("Enter number to check: ");
scanf("%d", &num);
int isEven = num % 2 == 0 ?
printf("%d is even", num) : printf("%d is odd", num);
}
Write a program to check if a number is even or odd using switch
#include <stdio.h>
void main() {
int num;
printf("Enter number to check: ");
scanf("%d", &num);
switch (num % 2)
{
case 0:
printf("%d is even", num);
break;
default:
printf("%d is odd", num);
}
}