Tuesday, October 21, 2014

LOOPS IN PL/SQL



Iteration: means repetition of a set of statements depending upon a condition test. Till the time a condition is true, set of statements are repeated again and again. As soon as the condition becomes false, the repetition stops. This is also known a looping.
Simple Loop: this loop begins with LOOP and End with END LOOP. This construct creates an infinite loop by default. In order to terminate this loop, we use the EXIT statement. Syntax:
LOOP
--STATEMENTS TO BE EXECUTED
END LOOP;

e.g write a program to input a no and print the table of that no.
declare
no number;
ctr number;
begin
no := &no;
ctr := 1;
loop
dbms_output.put_line(no * ctr);
ctr := ctr + 1;
exit when ctr > 10;
end loop;
end;

Numeric For Loop: this looping construct is used to repeat a set of instructions for a fixed no of times. Syntax
For ctr in [reverse] start .. end
Loop
--statements to be executed
end loop;

Write the code to print 1 to 10.
BEGIN
FOR I IN 1..10 LOOP
DBMS_OUTPUT.PUT_LINE(I);
END LOOP;
END;

WRITE THE CODE TO PRINT 10 TO 1.
BEGIN
FOR I IN REVERSE 1..10 LOOP
DBMS_OUTPUT.PUT_LINE(I);
END LOOP;
END;

Characteristics of numeric for loop:
Ø  Loop Index is automatically declared
Ø  Expressions in range scheme are evaluated once.
Ø  Loop Index is not modifiable.

WHILE LOOP: this looping construct is used to repeat a set of statements till a condition holds true, as well as condition becomes false, loop terminate.
While
Loop
--statements to be executed
End loop

Write a program to display the sum of digits in no:
Declare
no number;
tot number := 0;
rem number;
begin
no := &no;
while no > 0
loop
rem := no mod 10;
tot := tot + rem;
no := no – rem;
no := no /10;
end loop;
dbms_output.put_line(tot);
end;

NESTED LOOP: when a loop exists inside another loop is called nested loop.
Loop
.
Loop  
.
end loop;
end loop
WRITE A PL/SQL PROG TO PRINT THE TABLE BETWEEN NO’s 2 TO 10
BEGIN
FOR I IN 1..10 LOOP
FOR J IN 2..10 LOOP
DBMS_OUTPUT.PUT(I*J || ‘           ‘);
END LOOP;
DBMS_OUTPUT.NEW_LINE;
END LOOP;

No comments: