Sum of odd numbers using for loop in pl/sql

Sum of odd numbers using for loop in pl/SQL.

In this article, we will see how to write a PL/SQL program to get the sum of odd numbers using for loop in pl/SQL. Here you can check the query with output.

Sum of first odd number = 1 and the Sum of first two odd numbers = 1 + 3 = 4 (4 = 2 x 2). Sum of first three odd numbers = 1 + 3 + 5 = 9 (9 = 3 x 3) and the sum of first four odd numbers can be represented X = 1 + 3 + 5 + 7 = 16 (16 = 4 x 4).

So to achieve the sum of first n odd numbers we will apply odd number theorem, because it states that the sum of first n odd numbers is adequate to the square of n. If we apply odd number theorem: sum of first 10 odd numbers = n * n = 10 * 10 = 100

Sum of odd numbers pl/sql program

1 declare
2 num number;
3 sum_one number default 0;
4 lastvalue number;
5 begin
6 endvalue:=&lastvalue;
7 n:=1;
8 for n in 1..lastvalue
9 loop
10 if mod(n,2)=1
11 then
12 sum_one:=sum_one+n;
13 end if;
14 end loop;
15 dbms_output.put_line(‘ sum = ‘||sum_one);
16* end;

Output

SQL> /
Enter value for lastvalue: 9
old 6: lastvalue:=&lastvalue;
new 6: lastvalue:=9;

Sum = 25

Queries Solved

sum of odd numbers using for lool in sql

You May Also Like

Leave a comment