## Forum Stats

• 3,851,525 Users
• 2,263,993 Discussions

Discussions

# While Loop Error

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:

• 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.)

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

• 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.