Today’s task is to create a program that checks whether a number entered by the user is even or odd. This will introduce you to conditional statements (like if
and else
) which allow your program to make decisions based on the input.
An even number is divisible by 2 with no remainder, while an odd number has a remainder of 1 when divided by 2. The goal of today’s task is to check the remainder of the division and print a message indicating whether the number is even or odd.
%
).number % 2 == 0
number % 2 != 0
A conditional statement (like if
or else
) allows your program to execute different code depending on whether a condition is true or false. In this case, the condition is whether the number is divisible by 2.
Syntax:
Python:
if number % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")
Java:
if (number % 2 == 0) {
System.out.println("The number is even.");
} else {
System.out.println("The number is odd.");
}
JavaScript:
if (number % 2 === 0) {
console.log("The number is even.");
} else {
console.log("The number is odd.");
}
First, prompt the user to enter a number. Since the input from the user is usually a string, you will need to convert it to an integer before performing any calculations.
Python: Use input()
and convert the input to an integer using int()
.
number = int(input("Enter a number: "))
Java: Use Scanner
and capture the integer input with nextInt()
.
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
JavaScript: Use prompt()
to get the input and convert it to an integer using parseInt()
.
let number = parseInt(prompt("Enter a number:"));
%
) gives the remainder when a number is divided by another number. For example:5 % 2
will return 1
(because 5 divided by 2 leaves a remainder of 1).6 % 2
will return 0
(because 6 is evenly divisible by 2).This operator will help you determine if a number is even or odd.
print()
(Python), System.out.println()
(Java), or console.log()
(JavaScript) to display the result.4
, the output will be: The number is even.
7
, the output will be: The number is odd.
0 % 2 == 0
.if
and else
.Once you’ve successfully completed this task, you can expand your program:
This simple exercise will help you become more comfortable with basic conditionals and mathematical operations, which are essential for more complex programming challenges down the road.