Given an integer N, the task is to check if the given number N is even or odd. If it is found to be even, then print “Even”. Otherwise, print “Odd”.
Examples:
Input: N = 2
Output: EvenInput: N = 5
Output: Odd
Method 1: The simplest approach is to check if the remainder obtained after dividing the given number N by 2 is 0 or 1. If the remainder is 0, then print “Even”. Otherwise, print “Odd”.
Below is the implementation of the above approach:
C
// C program for the above approach #include <stdio.h> // Function to check if a // number is even or odd void checkEvenOdd( int N) { // Find remainder int r = N % 2; // Condition for even if (r == 0) { printf ( "Even" ); } // Otherwise else { printf ( "Odd" ); } } // Driver Code int main() { // Given number N int N = 101; // Function Call checkEvenOdd(N); return 0; } |
Odd
Time Complexity: O(1)
Auxiliary Space: O(1)
Method 2: Another approach is to use Bitwise Operators. The idea is to check whether the last bit of the given number N is 1 or not. To check whether the last bit is 1 find the value of (N & 1). If the result is 1, then print “Odd”. Otherwise, print “Even”.
Below is the illustration for N = 5:
N = 5.
Binary representation of 5 is 00000101
Binary representation of 1 is 00000001
——————————————————————-
The value of Bitwise AND is 00000001Since the result is 1. Therefore, the number N = 5 is odd.
Below is the implementation of the above approach:
C
// C program for the above approach #include <stdio.h> // Function to check if a // number is even or odd void checkEvenOdd( int N) { // If N & 1 is true if (N & 1) { printf ( "Odd" ); } // Otherwise else { printf ( "Even" ); } } // Driver Code int main() { // Given number N int N = 101; // Function Call checkEvenOdd(N); return 0; } |
Odd
Time Complexity: O(1)
Auxiliary Space: O(1)
Method 3: The idea is to initialize an integer variable var as 1 and change it from 1 to 0 and vice-versa alternately, N times. If var is equal to 1 after N operations, print “Even”. Otherwise, print “Odd”.
Below is the implementation of the above approach:
C
// C program for the above approach #include <stdio.h> // Function to check a number is // even or odd void checkEvenOdd( int N) { // Initialise a variable var int var = 1; // Iterate till N for ( int i = 1; i <= N; i++) { // Subtract var from 1 var = 1 - var; } // Condition for even if (var == 1) { printf ( "Even" ); } // Otherwise else { printf ( "Odd" ); } } // Driver Code int main() { // Given number N int N = 101; // Function Call checkEvenOdd(N); return 0; } |
Odd
Time Complexity: O(1)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.