p7 -- A recursive function create or replace function factorial( num in number) return number as begin if num = 0 then return 1; else return num * factorial(num - 1); end if; end; / -- This is how to call that function. declare z number; begin z := factorial(3); dbms_output.put_line(z); end; / -- When does it switch to scientific notation? -- When does it "break"? -- p7b -- A useful procedure. -- For lazy people. Like me. create or replace procedure pr( str in varchar2) as begin dbms_output.put_line(str); end; / begin pr('Listening to you I get the music'); pr(1234); end; / p8 -- The "loop - end loop" loop. -- An "almost endless" loop -- You need to jump out with exit. create or replace procedure vector as i number; begin i := 0; loop -- potentially an endless loop dbms_output.put_line(i); i := i + 1; exit when i = 10; -- This makes it "not endless" end loop; end; / begin vector; end; / -- Now do -- drop procedure vector -- and try the main program again. p9 -- This is a for loop, finally. -- The most important tool of all programmers. create or replace procedure matrix as i number; begin for i in 1 .. 10 loop dbms_output.put_line(i); end loop; end; / begin matrix; end; / p9b -- More examples of for loops create or replace procedure matrix as i number; begin for i in 10 .. 15 -- works loop dbms_output.put_line(i); end loop; for i in -5 .. 5 -- works loop dbms_output.put_line(i); end loop; for i in 20 .. 20 -- works, done once loop dbms_output.put_line(i); end loop; for i in 5 .. 4 -- Nothing happens loop dbms_output.put_line(i); end loop; for i in reverse 9 .. 6 -- Nothing happens loop dbms_output.put_line(i); end loop; for i in reverse 6 .. 9 -- works, counts down loop dbms_output.put_line(i); end loop; end; / begin matrix; end; / p10 -- More loops -- This is a nested for loop. create or replace procedure testnestedloop as i number; j number; line varchar2(80); begin for i in 1 .. 10 loop line := i || '::'; for j in 20 .. 30 loop line := line || ' ' || j; end loop; dbms_output.put_line(line); end loop; end; / begin testnestedloop; end; / p10b -- Print a triangle matrix. create or replace procedure matrix as i number; j number; line varchar2(80); begin for i in 1 .. 10 -- Count rows loop line := ''; for j in 1 .. i+1 -- Count columns in row loop line := line || ' ' || j; end loop; dbms_output.put_line(line); end loop; end; begin matrix; end; /