Floyd's triangle in PL/SQL


PL/SQL is a combination of SQL along with the procedural features of programming languages

FLOYD’s triangle − it is a triangle formed by natural numbers. It is the triangle formed by filling numbers in rows starting from 1 at the top-left corner. It is a right-angled triangle i.e. the count of numbers in each row is the same as the row number.

In this problem, we are given a natural number N. Our task is to create Floyd’s triangle in PL/SQL.

Let’s take an example to understand the problem

Input: 16
Output:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

Solution Approach

A solution to the problem is by looping till the count is smaller than N. Keeping a counter for the number of rows, we will increment the count after each row’s count is completed. And for each count, we will fill numbers equal to the row count. As PL/SQL is also a sort of programming language it allows us to perform such tasks.

Example

Program to illustrate the working of our solution

DECLARE
   n NUMBER := 1;
   prntVal VARCHAR2(200);

BEGIN
   FOR i IN 1..22 LOOP
      FOR j IN 1..i LOOP
         prntVal := prntVal
            ||' '
            ||n;
         n := n + 1;
         exit WHEN n = 16;
      END LOOP;

      dbms_output.Put_line(prntVal);
      exit WHEN n = 16;
      prntVal := NULL;
   END LOOP;
END;

Output

1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21

Updated on: 01-Feb-2022

354 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements