Search code examples
mysqlwhile-loopsumdo-while

how to calculate the sum of the first 100 integers in MySQL with a while loop


I must find the sum of the first 100 natural numbers. 1+2+3+...+n, and so on. While using "while loops".

delimiter $

create procedure `calcul`.somme()

begin

declare s int default 0;
declare i int default 1;

while(i<=100) do
    set s := s+i;
    set i := i+1;
end while;
select s;

end;
$
call `calcul`.somme()

when I call the somme() I'm getting this error -->

call calcul.somme()= Error Code: 2013. Lost connection to MySQL server during query


Solution

  • use calcul;
    delimiter $
    create procedure somme()
    begin
    
    
    declare s int default(0);
    declare i int default(1);
    
        while(i<=100) do
        set s := s+i;
        set i := i+1;
        end while;
    select s;
    end;
    $
    CALL somme()
    

    thanks, the Problem solved 👌