How to write a C Program to Check Odd or Even number using If Statement and Conditional Operator with an example of each?. If a number is divisible by 2, it is an even number, and the remaining (not divisible by 2) are odd numbers.
C Program to Check Odd or Even using IF Condition
This program allows the user to enter an integer. Next, this C program checks whether that number is even or odd using the If statement.
In C Programming, we have an Arithmetic Operator called % (Module) to check the remainder of the division. Let’s use this operator to find the remainder. If the remainder is 0, then the number is even else odd number.
/* C Program to Check Odd or Even using IF Condition */ #include<stdio.h> int main() { int number; printf(" Enter an int value to check Even or Odd \n"); scanf("%d", &number); if ( number%2 == 0 ) //Check whether remainder is 0 or not printf("Given number %d is EVEN NUMBER \n", number); else printf("Given number %d is ODD NUMBER \n", number); return 0; }
ANALYSIS
Within this C Odd or Even example, below printf statement will ask the user to Enter a value to check whether it is Even or Odd.
printf(" Enter an int value to check Even or Odd \n ");
Below scanf statement will assign the user entered a value to a number variable.
scanf(" %d ",&number);
In the Next line, We declared the If statement
if ( number % 2 == 0 )
Any number that is completely divisible 2 is even number. If condition check whether the remainder of the number divided by 2 is exactly equal to 0 or not.
- If the condition is True, it is Even number
- If the condition is False, it is an Odd number
Enter the second value to check for the even number
You can observe from the above c odd or even code that we used if condition to check whether the remainder of the given integer is 0 or not and print as per the result.
C Program to Check Even or Odd using Conditional Operator
We can also use the Conditional operator to check whether the number is even or odd in c programming. Let’s see the example program of this
/* C Program to Check Even or Odd Using Conditional Operator */ #include<stdio.h> int main() { int number; printf(" Enter an int value to check Even or Odd \n "); scanf("%d",&number); number%2 == 0 ? printf(" Even Number \n ") : printf(" Odd Number \n"); return 0; }