Related Articles

Related Articles

Print all even numbers from 1 to n in PL/SQL
  • Last Updated : 29 Jun, 2018

Prerequisite- PL/SQL Introduction

In PL/SQL code groups of commands are arranged within a block. It groups together 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 even numbers and their sum from 1 to N.

Examples:

Input: N = 3
Output: 2
Sum = 2

Input: N = 5
Output: 2, 4
Sum = 6

Approach is to initialize a number num with 2 and keep incrementing it by 2 until num is <= N.
Below is its implementation:

filter_none

edit
close

play_arrow

link
brightness_4
code

-- Display all even number from 1 to n
DECLARE
    -- Declare variable num
    num NUMBER(3) := 2;
    sum1 NUMBER(4) := 0;
BEGIN
    WHILE num <= 5 LOOP
  
        -- Display even number
        dbms_output.Put_line(num);
  
        -- Sum of even numbers
        sum1 := sum1 + num;
  
        -- Next even number
        num := num + 2;
          
  
    -- End  loop
    END LOOP;
  
    -- Display even number
        dbms_output.Put_line('Sum of even numbers is ' || sum1);
END;

chevron_right


Output:

2
4
Sum of even numbers is 6
My Personal Notes arrow_drop_up
Recommended Articles
Page :