Skip to Main Content

SQL & PL/SQL

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

While Loop Error

187babb6-aec4-4bc2-900f-d731a81d9d8cAug 6 2014 — edited Aug 6 2014

I'm learning Oracle

but I have a problem withn this exercise,  I need to this summation

3

∑  (X2 + 4)

N=1


and this is my code


DECLARE

x NUMBER(10) :=0;

z NUMBER;

suma NUMBER;

BEGIN

WHILE x<=3

LOOP

x :=x+1;

z := x*2+4;

suma := suma+z;

END LOOP;

DBMS_OUTPUT.PUT_LINE(suma);

END


what is my error ?



Thanks

Comments

Frank Kulash

Hi,

You need to initialize suma, like you initialize.x:

DECLARE

    x    NUMBER (10) := 1;

    z    NUMBER;

    suma NUMBER      := 0;

BEGIN

    WHILE x <= 3

    LOOP

        z := (x * 2) + 4;

        suma := suma + z;

        x := x + 1;

    END LOOP;

    DBMS_OUTPUT.PUT_LINE (suma || ' = final suma');

END;

/

NULL plus anything is NULL, so if suma is NULL when you reach this statement

suma := suma + z;

then it will be NULL after executing that statement.

Also, you're going through the loop an extra time.  Since x starts at 0, yu're starting the loop when x is 0, 1, 2 and 3, and incrementing the sum for x as 1, 2, 3 and 4.

(I see Galo caught the same thing while I was revising this message.)

Galo Balda

Another thing is that you're doing 4 iterations since x starts with 0

Frank Kulash

Hi,

You can do this in pure SQL, too:

SELECT  SUM ((2 * LEVEL) + 4)  AS suma

FROM    dual

CONNECT BY  LEVEL  <= 3

;

1 - 3
Locked Post
New comments cannot be posted to this locked post.

Post Details

Locked on Sep 3 2014
Added on Aug 6 2014
3 comments
154 views