Lab 8.3 Exercises


8.3.1 Use Numeric FOR Loops with the IN Option

In this exercise, you will use a numeric FOR loop to calculate a factorial of 10 (10! = 1*2*3 *10).

Create the following PL/SQL script:

 
 -- ch08_4a.sql, version 1.0 SET SERVEROUTPUT ON DECLARE    v_factorial NUMBER := 1; BEGIN    FOR v_counter IN 1..10 LOOP       v_factorial := v_factorial * v_counter;    END LOOP;    -- control resumes here    DBMS_OUTPUT.PUT_LINE ('Factorial of ten is: '       v_factorial); END; 

Execute the script, and then answer the following questions:

a)

What output was printed on the screen?

b)

How many times was the loop executed?

c)

What is the value of the loop counter before the loop?

d)

What is the value of the loop counter after the loop?

e)

How many times will the loop be executed if the value of v_counter is incremented by 5 inside the body of the loop?

f)

Rewrite this script using the REVERSE option. What will the value of v_factorial be after the loop is completed?


8.3.2 Use Numeric FOR Loops with the REVERSE Option

In this exercise, you will use the REVERSE option to specify the range of numbers used by the loop to iterate. You will display a list of even numbers starting from 10 going down to 0. Try to answer the questions before you run the script. Once you have answered the questions, run the script and check your results.

Create the following PL/SQL script:

 
 -- ch08_5a.sql, version 1.0 SET SERVEROUTPUT ON BEGIN    FOR v_counter IN REVERSE 0..10 LOOP       -- if v_counter is even, display its value on the       -- screen       IF MOD(v_counter, 2) = 0 THEN          DBMS_OUTPUT.PUT_LINE ('v_counter = 'v_counter);       END IF;    END LOOP;    -- control resumes here    DBMS_OUTPUT.PUT_LINE ('Done...'); END; 

As in the previous exercises, answer the following questions first, and then execute the script:

a)

What output will be printed on the screen?

b)

How many times will the body of the loop be executed?

c)

How many times will the value of v_counter be displayed on the screen?

d)

How would you change this script to start the list from 0 and go up to 10?

e)

How would you change the script to display only odd numbers on the screen?

f)

How many times will the loop be executed in this case?




Oracle PL[s]SQL by Example
Oracle PL[s]SQL by Example
ISBN: 3642256902
EAN: N/A
Year: 2003
Pages: 289

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net