Forum Stats

  • 3,770,031 Users
  • 2,253,051 Discussions
  • 7,875,275 Comments

Discussions

While Loop Error

187babb6-aec4-4bc2-900f-d731a81d9d8c
edited Aug 6, 2014 6:03PM in SQL & PL/SQL

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

Tagged:

Answers

  • Frank Kulash
    Frank Kulash Member, Moderator Posts: 41,232 Red Diamond
    edited Aug 6, 2014 6:00PM

    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
    Galo Balda Member Posts: 172

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

  • Frank Kulash
    Frank Kulash Member, Moderator Posts: 41,232 Red Diamond
    edited Aug 6, 2014 6:03PM

    Hi,

    You can do this in pure SQL, too:

    SELECT  SUM ((2 * LEVEL) + 4)  AS suma
    FROM    dual
    CONNECT BY  LEVEL  <= 3
    ;
    
    
This discussion has been closed.