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

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.
Examples:

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 digts, if it is odd or even.

Below is the required implementation:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

Odd Digits: 3
Even Digits: 3


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.