Table of Contents
Algorithm
the algorithm to determine whether a given number is even or odd:
- Start
- Read the input number from the user and store it in a variable, let’s call it
num
. - Check if
num
modulo 2 is equal to 0.- If the condition is true, the number is even.
- If the condition is false, the number is odd.
- Display the result indicating whether the number is even or odd.
- End
By following this algorithm, you can implement a program in any programming language to determine whether a given number is even or odd.
C program
#include <stdio.h> int main() { int num; printf("Enter a number: "); scanf("%d", &num); if (num % 2 == 0) { printf("The number is even.\n"); } else { printf("The number is odd.\n"); } return 0; }
C++
#include <iostream> int main() { int num; std::cout << "Enter a number: "; std::cin >> num; if (num % 2 == 0) { std::cout << "The number is even." << std::endl; } else { std::cout << "The number is odd." << std::endl; } return 0; }
Both the C and C++ programs follow the same logic. They prompt the user to enter a number, read it using scanf
in C and std::cin
in C++, and store it in the variable num
.
Then, they use an if statement to check if the number is divisible by 2 using the modulo operator %
. If the remainder is 0, it means the number is even. Otherwise, it is odd.
Finally, they display the result using printf
in C and std::cout
in C++.
Java
import java.util.Scanner; public class EvenOddChecker { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a number: "); int num = scanner.nextInt(); if (num % 2 == 0) { System.out.println("The number is even."); } else { System.out.println("The number is odd."); } scanner.close(); } }
In this Java program, we use the Scanner
class to read the input from the user. The program prompts the user to enter a number and stores it in the variable num
.
Then, we use an if statement to check if the number is divisible by 2 using the modulo operator %
. If the remainder is 0, it means the number is even. Otherwise, it is odd.
Finally, we display the result using System.out.println()
.
Remember to import the java.util.Scanner
class at the beginning of your program to use the Scanner
class for input reading.
num = int(input("Enter a number: ")) if num % 2 == 0: print("The number is even.") else: print("The number is odd.")
In this program, the user is prompted to enter a number using the input()
function, and the number is stored in the variable num
after converting it to an integer using the int()
function.
Then, an if statement is used to check if the number is divisible by 2. The modulo operator %
is used to calculate the remainder when num
is divided by 2. If the remainder is 0, it means the number is even. Otherwise, it is odd.
Finally, the program uses the print()
function to display the result indicating whether the number is even or odd.