Experiment No 19: Implement PL/SQL program using Iterative Statements
Experiment No 19: Implement PL/SQL program using Iterative Statements
Result
The PL/SQL programs using Basic Loop, For Loop, and While Loop were successfully executed, demonstrating their functionality and differences.
Q1. List Iterative statements in PL/SQL.
In PL/SQL, the iterative statements (loops) are:
-
Basic Loop
-
FOR Loop
-
WHILE Loop
Q2. Write PL/SQL program using any one Iterative statement.
Here’s an Oracle-ready PL/SQL program using the FOR Loop to print numbers from 1 to 10.
-- Enable output
SET SERVEROUTPUT ON;
DECLARE
i NUMBER(2);
BEGIN
FOR i IN 1..10 LOOP
DBMS_OUTPUT.PUT_LINE('Number: ' || i);
END LOOP;
END;
/
Expected Output
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Number: 6
Number: 7
Number: 8
Number: 9
Number: 10
Exercise
a. Multiplication Table of 5 using FOR loop
SET SERVEROUTPUT ON;
DECLARE
i NUMBER(2);
BEGIN
DBMS_OUTPUT.PUT_LINE('Multiplication Table of 5');
FOR i IN 1..10 LOOP
DBMS_OUTPUT.PUT_LINE('5 x ' || i || ' = ' || (5 * i));
END LOOP;
END;
/
Expected Output (sample)
Multiplication Table of 5
5 x 1 = 5
5 x 2 = 10
...
5 x 10 = 50
b. Factorial of 10 using WHILE loop
SET SERVEROUTPUT ON;
DECLARE
num NUMBER := 10;
fact NUMBER := 1;
BEGIN
WHILE num > 0 LOOP
fact := fact * num;
num := num - 1;
END LOOP;
DBMS_OUTPUT.PUT_LINE('Factorial of 10 is: ' || fact);
END;
/
Expected Output
Factorial of 10 is: 3628800
c. Prime Numbers between 1 to 50
SET SERVEROUTPUT ON;
DECLARE
i NUMBER;
j NUMBER;
flag BOOLEAN;
BEGIN
DBMS_OUTPUT.PUT_LINE('Prime numbers between 1 and 50:');
FOR i IN 2..50 LOOP
flag := TRUE;
j := 2;
WHILE j <= i/2 LOOP
IF MOD(i, j) = 0 THEN
flag := FALSE;
EXIT;
END IF;
j := j + 1;
END LOOP;
IF flag THEN
DBMS_OUTPUT.PUT_LINE(i);
END IF;
END LOOP;
END;
/
Expected Output
Prime numbers between 1 and 50:
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47