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
DECLARE
num NUMBER := 123456;
len VARCHAR2(20);
cnt1 NUMBER(5) := 0;
cnt2 NUMBER(5) := 0;
BEGIN
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;
dbms_output.Put_line( 'Odd Digits: '
|| cnt1);
dbms_output.Put_line( 'Even Digits: '
|| cnt2);
END ;
|
Output:
Odd Digits: 3
Even Digits: 3