SQL Tutorial

SQL Clauses / Operators

SQL-Injection

SQL Functions

SQL Queries

PL/SQL

MySQL

SQL Server

Misc

Centered triangular number in PL/SQL

A centered triangular number is a centered figurate number that represents a triangle with a dot in the center and all other dots surrounding the center in successive triangular layers. The n-th centered triangular number is given by the formula:

CT​(n)=3n2−3n+1

To compute the centered triangular number in PL/SQL, you can create a function as shown below:

CREATE OR REPLACE FUNCTION CenteredTriangularNumber(n NUMBER) RETURN NUMBER IS
    result NUMBER;
BEGIN
    result := (3 * n * n) - (3 * n) + 1;
    RETURN result;
END CenteredTriangularNumber;
/

To use the function, you can create a PL/SQL block:

DECLARE
    n       NUMBER := 5;   -- change this value to compute the centered triangular number for a different n
    ct_num  NUMBER;
BEGIN
    ct_num := CenteredTriangularNumber(n);
    DBMS_OUTPUT.PUT_LINE('Centered Triangular Number for n=' || n || ' is: ' || ct_num);
END;
/

Run the above block after defining the function to get the centered triangular number for a specific n. Adjust the value of n in the DECLARE section as needed.

  1. PL/SQL program for centered triangular number:

    Centered triangular numbers are generated by the formula: Cn = n * (n + 1) / 2. Here's a PL/SQL program to calculate the centered triangular number for a given input:

    CREATE OR REPLACE PROCEDURE centered_triangular_number(p_n IN NUMBER) IS
       v_result NUMBER;
    BEGIN
       v_result := p_n * (p_n + 1) / 2;
       DBMS_OUTPUT.PUT_LINE('Centered Triangular Number for ' || p_n || ' is: ' || v_result);
    END;
    /
    
  2. Calculating centered triangular numbers in Oracle SQL:

    If you want to calculate centered triangular numbers directly in a SQL query, you can use the following:

    SELECT n * (n + 1) / 2 AS centered_triangular_number
    FROM your_table_name;
    
  3. Centered triangular number sequence in Oracle SQL:

    To get a sequence of centered triangular numbers, you can use the following SQL query:

    SELECT LEVEL AS n, LEVEL * (LEVEL + 1) / 2 AS centered_triangular_number
    FROM dual
    CONNECT BY LEVEL <= your_limit;
    

    Replace your_limit with the desired number of rows in the sequence.