The program checks whether an entered number is even or odd. A number is considered as even number if it is divisible by 2, otherwise, it would be treated as an odd number.
There are various ways to achieve this functionality. In this article, we’ll be using two ways :
1) Using if and else
2) Using ternary Operator
Program :
#include <stdio.h> int main() { int number ; printf("Please enter a number : "); scanf("%d", &number); if(number % 2 == 0) { printf("%d is an even number.", number); } else{ printf("%d is an odd number.", number); } return 0; }
Output:
In the case of Even number input :
Please enter a number : 28 28 is an even number.
In case of Odd number input :
Please enter a number : 7 7 is an odd number.
Explanation:
In the above example, we have used if and else statement to check a number is even or odd. If number % 2, produces result as 0, then if block would be executed to print “even number message” on output screen, otherwise, else condition would be executed.
Program:
#include<stdio.h> #include<conio.h> void main() { int number; clrscr(); printf("\nPlease enter a number ="); scanf("%d",&number); (number%2)==0?printf("\n %d is even",number):printf("\n %d is odd",number); getch(); }
Output:
In case of even:
Please enter a number =20 20 is even
In case of odd:
Please enter a number =101 101 is odd
In above code, we used same approach, but this time with the help of ternary operator to find a number is even or odd.
Approach :
This post was last modified on August 12, 2022