Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Count odd and even digits in a number in PL/SQL

  • Last Updated : 11 Aug, 2021

Prerequisite PL/SQL introduction 
In PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations.
Given a number and task is to find the number of odd and even digits present in the number. 


Attention reader! Don’t stop learning now. Learn SQL for interviews using SQL Course  by GeeksforGeeks.

Input: 123456
Output: Odd digits = 3
        Even digits = 3

Input: 246
Output: Odd digits = 0
        Even digits = 3

Approach is to take a number and one by one check its digits, if it is odd or even.
Below is the required implementation: 


--Odd and Even digits in a number
--in PL/SQL
  --num variable declared
  --num assign with a number
  num NUMBER := 123456;
  --len variable char declared
  len VARCHAR2(20);
  --cntvariable declared
  cnt1 NUMBER(5) := 0;
  cnt2 NUMBER(5) := 0;
  --for loop go from 1 to length of the number
  FOR i IN 1..Length(num)
    len := Substr(num, i, 1);
    IF mod(len, 2) != 0 THEN
      cnt1 := cnt1 + 1;
    END IF;
  --end loop
  dbms_output.Put_line('Odd Digits: '
  || cnt1);
  dbms_output.Put_line('Even Digits: '
  || cnt2);
  --display result
--end program


Odd Digits: 3
Even Digits: 3
My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!