Search code examples
plsqlsumplsqldeveloper

Print sum of n numbers in plsql


CREATE OR REPLACE FUNCTION printsum(n IN number) IS
res number:=0;
BEGIN
while(n>0)
LOOP
res:=res+n;
n:=n-1;
EXIT WHEN n=0;
END LOOP;
dbms_output.put_line(' result of sum: '||res);
END;
/

I'm trying to print sum of n numbers, but I'm getting the following error:

Warning: Function created with compilation errors.


Solution

  • There are few errors in your code.

    1) Function must have a Return but your code had missing Return statement at beginning and at end.

    2) IN parameter cannot be reassigned inside the code. So you need to copy the IN parameter to a variable to iterate.

    Try this:

    CREATE OR REPLACE FUNCTION printsum( n IN NUMBER)
        RETURN NUMBER
      IS
        res   NUMBER:=0;
        v_num NUMBER:=n;
      BEGIN        
        WHILE(v_num>0)
        LOOP
          res   := res   + v_num;
          v_num := v_num -1;
          EXIT  WHEN v_num=0;        
        END LOOP;
    
        dbms_output.put_line(' result of sum: '||res);
    
        RETURN(res);      
      END;
      / 
    

    Output:

    SQL> select printsum(10) from dual;
    
    PRINTSUM(10)
    ------------
              55