Advertisement

Latest Post

Monday, 2 January 2017

How to Print a Triangle of stars in SQL

How to print a triangle of stars using SQL

Following is the simple sql server code that print a triangle of stars

DECLARE @I INT,@J INT,@DIFFERENCE INT
 SELECT @I=0,@J=10,@DIFFERENCE=2--DIFERRENCE BETWEEN CONSECUTIVE ROWS
 WHILE @I<@J
 BEGIN
    IF @I=0 AND @DIFFERENCE<>1
       PRINT SPACE((@J-@I)*@DIFFERENCE-1)+REPLICATE('*',1)
    ELSE IF(@DIFFERENCE%2=0)
       PRINT SPACE((@J-@I)*@DIFFERENCE)+REPLICATE('* ',@I+(@I*(@DIFFERENCE-1)))
    ELSE
       PRINT SPACE((@J-@I)*@DIFFERENCE)+REPLICATE('* ',@I+(@I*(@DIFFERENCE-1)))
    SELECT @I=@I+1
 END

Output:-
                   *
                  * * 
                * * * * 
              * * * * * * 
            * * * * * * * * 
          * * * * * * * * * * 
        * * * * * * * * * * * * 
      * * * * * * * * * * * * * * 
    * * * * * * * * * * * * * * * * 
  * * * * * * * * * * * * * * * * * * 

Government Jobs