16

Can anyone explain this PL / SQL statement in detail?

 3 years ago
source link: https://www.codesd.com/item/can-anyone-explain-this-pl-sql-statement-in-detail.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Can anyone explain this PL / SQL statement in detail?

advertisements
DECLARE
    p NUMBER := 0;
    q NUMBER := 1;
    r NUMBER;
BEGIN
    DBMS_OUTPUT.PUT_LINE(LPAD('0: ', 4) || LPAD(p, 10));
    DBMS_OUTPUT.PUT_LINE(LPAD('1: ', 4) || LPAD(q, 10));
    FOR k IN 2..20 LOOP
        r := p + q;
            DBMS_OUTPUT.PUT_LINE(LPAD(k, 2) || ': ' || LPAD(r, 10));
            p := q;
            q := r;
    END LOOP;
END;

We went over this in one of my classes but I didnt really get a good understanding to how this for loop works. I know the output prints numbers 0-20 on the left and I am confused at how the numbers on the right increase as they do.


the sequence printed are the fibonacci numbers. their recursive definition reads: a_n = a_(n-1) + a_(n-2). in the code snippet, p takes the role of a_(n-2), q that of a_(n-1). imagine the sequence printed out from the right to the left with a sliding window (r, q, p) superimposed. in each iteration, the window moves one step to the left. the lpad function pads a string to the given length. you may optionally add a 3rd argument, the padding character (defaults to ). notet that there is a sibling function rpad. but you probably know this if the code has been discussed in class.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK