Determining if a number is odd or even is a fundamental programming exercise. In PL/SQL, this is very easy to do and is the perfect way to learn about conditional logic (IF...THEN...ELSE) and the MOD function.
This simple guide will show you the logic and a complete program to solve this problem.
What is the Logic for Odd or Even?
The logic is based on a simple mathematical rule:
- An even number is a whole number that is perfectly divisible by 2 (it has a remainder of 0).
- An odd number is a whole number that has a remainder of 1 when divided by 2.
In Oracle, the MOD(n, 2) function is the perfect tool for this. It returns the remainder of n divided by 2.
What You Need to Know
To write this program, you will use a few basic PL/SQL concepts:
- Enabling Output: You must run this command once in your SQL tool (like SQL*Plus or SQL Developer) to see the printed results:
SET SERVEROUTPUT ON; - Anonymous Block: We will write our code in a
DECLARE...BEGIN...END;block. - Variables: We'll need a variable for the number we want to check (e.g.,
n NUMBER := 17;). MODFunction: The key to the program.MOD(n, 2)will return0ifnis even and1ifnis odd.IF...THEN...ELSELogic: We'll use this to check the result of theMODfunction and print the correct message.- Printing the Result: We use
DBMS_OUTPUT.PUT_LINE()to print the answer.
PL/SQL Program: Check for Odd or Even
This program will check the number stored in the n variable and print whether it is odd or even.
PL/SQL Program
SET SERVEROUTPUT ON;
DECLARE
-- The number we want to test
n NUMBER := 17;
BEGIN
-- Check if the remainder (MOD) of n / 2 is 0
IF MOD(n, 2) = 0 THEN
-- If the remainder is 0, the number is even
DBMS_OUTPUT.PUT_LINE(n || ' is an EVEN number.');
ELSE
-- If the remainder is anything else (like 1), the number is odd
DBMS_OUTPUT.PUT_LINE(n || ' is an ODD number.');
END IF;
END;
/
Result (for n := 17)
17 is an ODD number.
Result (if you change to n := 20)
20 is an EVEN number.
Program Explanation
DECLAREsection: We create one variable,n, and assign it the value17.BEGINsection: The program's logic starts.IF MOD(n, 2) = 0 THEN: This is the main check.- The program first calculates
MOD(17, 2), which returns the remainder1. - It then checks if
1 = 0. This isFALSE.
- The program first calculates
ELSE: Because theIFcondition wasFALSE, the program skips theTHENblock and runs theELSEblock.DBMS_OUTPUT.PUT_LINE(...): The program prints the string'17 is an ODD number.'.END IF;andEND;: TheIFblock and the main program block are closed.
