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 digits, if it is odd or even.
Below is the required implementation:
SQL
--Odd and Even digits in a number --in PL/SQL DECLARE --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; 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 |
Output:
Odd Digits: 3 Even Digits: 3
Please Login to comment...