In this problem, we are given a number n and we have to print all odd numbers from 1 to n and also print the sum of numbers from 1 to n in PL/SQL.
PL/SQL is a procedural language extension to SQL. The code is a sequence of instructions that are ground in a block with all related declarations and instructions.
Let’s see an example of our problem −
Input: 7 Output: odd numbers are: 1, 3, 5, 7 Sum of odd numbers is 16
To solve this problem, we will take a number and initialize it to 1 and a sum variable with initial value 0. And we will increase the number by 2 and add into the sum variable until its value is less than or equal to n.
Example
DECLARE number NUMBER(3) := 1; sumvar NUMBER(4) := 0; BEGIN dbms_output.Put_line('The odd numbers are : '); WHILE num <= 7 LOOP dbms_output.Put_line(number); sumvar := sumvar+num; num := num + 2; END LOOP; dbms_output.Put_line('Sum of odd numbers is '|| sum1); END;
Output
The odd numbers are −
1 3 5 7 Sum of odd numbers is 16