Hackerrank – Draw The triangle 1 (SQL Solution with Explanation)

Hackerrank Problem – Draw The Triangle 1

P(R) represents a pattern drawn by Julia in R rows. The following pattern represents P(5):

* * * * *
* * * *
* * *
* *
*

Write a query to print the pattern P(20).

The Solution

Delimiter //

CREATE PROCEDURE draw_triangle(i int)
   BEGIN
      WHILE i > 0 DO
          SELECT REPEAT('* ', i);
          SET i = i - 1;
      END WHILE;
   END//
  
Delimiter ;

CALL draw_triangle(20);

Output

* * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * *
* * * * * * * * *
* * * * * * * *
* * * * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*

Explanation

Delimiter //: This sets a custom delimiter to // temporarily. It allows us to write the procedure without SQL thinking we’re ending the statements prematurely.

CREATE PROCEDURE draw_triangle(i int): This line starts the definition of our stored procedure called draw_triangle. It takes one parameter i, which will represent the number of rows in our triangle.

BEGIN: This keyword marks the beginning of the procedure’s body.

WHILE i > 0 DO: Here, we start a loop that continues as long as the value of i is greater than 0.

SELECT REPEAT(‘* ‘, i);: Inside the loop, this line selects a string of stars (‘* ‘) repeated i times. This will form one row of the triangle. For example, if i is 5, it will select ‘* * * * * ‘.

SET i = i – 1;: After selecting a row of stars, we decrement the value of i by 1. This step is important because it helps us move towards the apex of the triangle, reducing the number of stars in each row.

END WHILE;: This marks the end of the loop.

END//: This is the end of the stored procedure definition, and we use // as our custom delimiter to indicate the end of the procedure.

Delimiter ;: Finally, we reset the delimiter to the default ;.

CALL draw_triangle(20);: This line calls the draw_triangle stored procedure with an argument of 20, meaning it will draw a triangle with 20 rows of stars.

Other HackerRank Solutions

In summary, this code defines a stored procedure that draws a triangular pattern of stars by looping through rows and decreasing the number of stars in each subsequent row until reaching the apex of the triangle. You can call this procedure with different values of i to draw triangles of varying heights.

:

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top