SQL Tutorial

SQL Clauses / Operators

SQL-Injection

SQL Functions

SQL Queries

PL/SQL

MySQL

SQL Server

Misc

Floyd’s triangle in PL/SQL

Floyd's Triangle is a series of natural numbers printed in a right-angled triangular shape. The numbers are printed sequentially, row after row.

For example, the Floyd's Triangle for 4 rows is:

1 
2 3 
4 5 6 
7 8 9 10

Here's how you can generate Floyd's Triangle in PL/SQL for n rows:

DECLARE 
    n NUMBER := 4; -- Number of rows
    current_num NUMBER := 1;
BEGIN 
    FOR i IN 1..n LOOP
        FOR j IN 1..i LOOP
            DBMS_OUTPUT.PUT(current_num || ' ');
            current_num := current_num + 1;
        END LOOP;
        DBMS_OUTPUT.NEW_LINE;
    END LOOP;
END;
/

In this script, we use two nested loops. The outer loop represents each row, while the inner loop prints the numbers for each row. The variable current_num keeps track of the current number to be printed. Adjust the value of n to change the number of rows in the triangle.

  1. Generating Floyd's Triangle in Oracle SQL:

    SELECT LEVEL, LPAD(' ', (LEVEL - 1) * 2, ' ') || LEVEL AS FloydNumber
    FROM dual
    CONNECT BY LEVEL <= 5; -- Change this to the desired number of rows
    
  2. Floyd's Triangle Pattern Using PL/SQL Nested Loops:

    DECLARE
        n INTEGER := 5; -- Change this to the desired number of rows
    BEGIN
        FOR i IN 1..n LOOP
            FOR j IN 1..i LOOP
                DBMS_OUTPUT.PUT(j || ' ');
            END LOOP;
            DBMS_OUTPUT.NEW_LINE;
        END LOOP;
    END;
    /
    
  3. Printing Floyd's Triangle in a PL/SQL Procedure:

    CREATE OR REPLACE PROCEDURE PrintFloydsTriangle(p_rows IN INTEGER) IS
    BEGIN
        FOR i IN 1..p_rows LOOP
            FOR j IN 1..i LOOP
                DBMS_OUTPUT.PUT(j || ' ');
            END LOOP;
            DBMS_OUTPUT.NEW_LINE;
        END LOOP;
    END;
    /