Home » SQL & PL/SQL » SQL & PL/SQL » pl/sql-equation
pl/sql-equation [message #1318] Sat, 20 April 2002 12:14 Go to next message
Mark
Messages: 284
Registered: July 1998
Senior Member
Hello, I'm trying to sum all the even numbers from 1 to 1000. i.e. 2+4+6+8+10 =30..I accumulate but when the loop goes to the top, the variable is cleared and the last loop value is displayed. The code below is what I'm using. Can I get a variable to hold the accumulated value so that at the end of the loop it displays the total sum of all the looped values? Thanks for the help.

set serveroutput on
DECLARE
TOTAL NUMBER;
TTOTAL NUMBER;
BEGIN

FOR I IN 1..1000 LOOP
IF mod(I,2)=0 then
total:=I + I;
ttotal:=total + I;
END IF;
END LOOP;

DBMS_OUTPUT.PUT_LINE('Total sum of even numbers: '||ttotal);
END;
/
Re: pl/sql-equation [message #1340 is a reply to message #1318] Tue, 23 April 2002 01:08 Go to previous message
John R
Messages: 156
Registered: March 2000
Senior Member
Well, your maths in the middle of the loop is totally stuffed, but other than that the code's fine.

Your code is simply setting TOTAL to double the current value of I and then overwriting TTOTAL with the value TOTAL+I (which is 3*I)

Try using this:

DECLARE
TOTAL NUMBER := 0;
BEGIN

FOR I IN 1..1000 LOOP
IF mod(I,2)=0 then
total:=total + I;
END IF;
END LOOP;

DBMS_OUTPUT.PUT_LINE('Total sum of even numbers: '||total);
END;
Previous Topic: Simple SQL Question
Next Topic: Where 1 = 2
Goto Forum:
  


Current Time: Thu Apr 25 01:34:05 CDT 2024