Introduction
This blog will discuss how to write a program to check whether the number is even or odd.
We are given a number, and we need to state whether the number is even or odd.
Example 1:
Sample Input:
a=5
Sample Output:
Odd
Example 2:
Sample Input:
a=6
Sample Output:
Even
Approach
The approach to write a program to check whether the number is even or odd is given below. Check whether the number, when divided by 2, yields the remainder 0. If the remainder is 0, then it’s an even number else, it’s an odd number.
Time Complexity for writing a program to check whether the number is even or odd = O(1).
It takes constant time.
Till now, I assume you must have got the basic idea of what has been asked in the problem statement. So, I strongly recommend you first give it a try. even or odd
Pseudo Code
Algorithm
________________________________________________________________
procedure evenodd():
___________________________________________________________________
1. Declare n, rem
2. rem=n%2
3. if(rem==0): even
4. Else: odd
5. Display even or odd
end procedure
___________________________________________________________________
Implementation in C++
#include<iostream>
using namespace std;
int main()
{
int n, rem;
cout << "Enter the number : ";
cin >> n;
//checking for the remainder
rem = n % 2;
if (rem == 0)
cout << "even" << endl;
else
cout << "odd" << endl;
return 0;
}
Output:
Sample Input:
Enter the number : 5
Sample Output:
odd
Complexity Analysis
Time Complexity: O(1), Since no extra operation, constant time is taken.
Space complexity: O(1), no extra variable used.
Read More - Time Complexity of Sorting Algorithms