How to print a pascal triangle with '*' in Oracle using Pl/SQL functions, I am expecting to write in minimal lines of code. Can anyone help me ? This is what I tried,
begin
for i in 1..5 loop
dbms_output.put_line('');
for j in 1..i loop
dbms_output.put('*');
end loop;
end loop;
end;
I have an answer with two for loops to print a triangle, but I am trying to finish with one for loop using Lpad() and Rpad() functions.
This is a great opportunity to show how one can approach a problem logically when one does not have any idea how to proceed. No one is here to do homework for you, but we can give some pointers on approaching a problem, then help guide when we see what you come up with.
Start with the end result desired and work backward to figure out what to do to get the desired result. What do you expect the output to be? Something like this (for 4 rows)?:
*
* *
* * *
* * * *
Do you notice a recurring pattern? "recurring pattern" indicates a loop of some sort will be required. Perhaps if you replace the leading spaces with another character, another recurring pattern will become obvious:
XXX*
XX* *
X* * *
* * * *
So, a recurring pattern within another recurring pattern. What is the relationship between the number of leading spaces to the number of '*'s in the row? The need for a calculation or two may become apparent, depending on the row. That is about all I want to give away, as the point of the assignment is for you to figure it out.
Hopefully this provided a nudge on how to approach solving a problem without giving too much away.
Edit 6/27/2022 Yeah I know this is old, but since it's been answered I thought it would be fun to do with a recursive CTE query:
COLUMN C FORMAT a30;
WITH GenTriangle(TotRows, CurRow, StrOut) AS (
SELECT 6, 0, NULL FROM dual
UNION ALL
SELECT 6, CurRow + 1, LPAD(' ', TotRows - (CurRow + 1), ' ') || RPAD('*', ((CurRow + 1) * 2) - 1, '*')
FROM GenTriangle
WHERE CurRow + 1 <= TotRows
)
SELECT StrOut AS triangle FROM GenTriangle;
TRIANGLE
--------------------------------------
*
***
*****
*******
*********
***********
7 rows selected.