Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

Print all odd numbers and their sum from 1 to n in PL/SQL

  • Last Updated : 02 Jul, 2018

Prerequisite PL/SQL introduction
In PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations.

Given a number N, the task is to display all the odd numbers from 1 to N and their sum.

Attention reader! Don’t stop learning now. Learn SQL for interviews using SQL Course  by GeeksforGeeks.


Input: 3
Output: 1, 3

Input: 5
Output: 1, 3, 5

Approach is to initialize a num with 1 and sum with 0 and keep incrementing num by 2 and sum by num until num <= N.

-- display all odd number from 1 to n
    -- declare variable num
    num NUMBER(3) := 1;
    sum1 NUMBER(4) := 0;
    WHILE num <= 5 LOOP
        -- display odd number
        -- the sum of all odd numbers
         sum1 := sum1 + num;
        --next odd number
        num := num + 2;
    -- end  loop
dbms_output.Put_line('Sum of all odd numbers is '|| sum1);


Sum of all odd numbers is 9
My Personal Notes arrow_drop_up
Recommended Articles
Page :