Practice › Basics
Even or Odd
Easy · Basics · Asked at TCS, Infosys, Wipro, Accenture, Cognizant
Given an integer n, print Even if it is even, otherwise print Odd.
Input
One integer n.
Output
Even or Odd.
Constraints
- -10^9 ≤ n ≤ 10^9
Careful with negative numbers: in C++/Java
-3 % 2is-1, not1.
Example 1
Input
4
Output
Even
Example 2
Input
7
Output
Odd
Hints
- A number is even when it is divisible by 2.
- For negative n, n % 2 is -1 in C++/Java. Compare with 0 instead of 1.
Approach
Check n % 2 == 0. Testing n % 2 == 1 is a common bug: in C++ and Java the remainder keeps the sign of n, so -3 % 2 is -1 and the odd check would fail. Comparing against 0 works for every sign.
Complexity: O(1) time · O(1) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
long long n;
cin >> n;
cout << (n % 2 == 0 ? "Even" : "Odd") << "\n";
return 0;
}Python solution
n = int(input())
print("Even" if n % 2 == 0 else "Odd")Java solution
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long n = sc.nextLong();
System.out.println(n % 2 == 0 ? "Even" : "Odd");
}
}