Check odd or even using modulus operator
Even numbers are always divisible by 2. If you do the modulo operation on the given number with 2 and the reminder is 0,then the number is even, otherwise, odd. This principle is applied in the following program.
#include <stdio.h> void main() { int num = 0; printf("Enter an integer: "); scanf("%d", &num); if (num%2 == 0) { printf("%d is an even number.\n", num); } else { printf("%d is an odd number.\n", num); } }
C program to check odd or even using bitwise operator
The least significant bit of an even number is always 0. Similar thing applied for the odd numbers. Least significant bit of an odd number is always 1. If you do bitwise AND operation between the given number and 1 and the result becomes 0, then the least significant bit of the number is 0. That means the number is even. Similarly, if the result becomes 1, the number is odd. This principle is applied in the following program.
#include <stdio.h> void main() { int num = 0; printf("Enter an integer: "); scanf("%d", &num); if (num & 1 == 0) { printf("%d is an even number.\n", num); } else { printf("%d is an odd number.\n", num); } }
C program to check odd or even without using bitwise or modulus operator
#include <stdio.h> void main() { int num = 0; printf("Enter an integer: "); scanf("%d", &num); if ((n/2)*2 == n) { printf("%d is an even number.\n", num); } else { printf("%d is an odd number.\n", num); } }
Output:
Enter an integer: 234 234 is an event number. Enter an integer: 2231 2231 is an odd number.
The post C Program to Check Whether a Number is Odd or Even appeared first on QnA Plus.