Wednesday, February 3, 2021

 

Printing Star (*) Pattern using SQL

   Part - 26

--*********************************************************
-- 26 - Printing Star (*) Pattern using SQL
--*********************************************************

Click below for you tube answer:











-- REPLICATE --> 

SELECT REPLICATE('String ',6) AS Derived_String
SELECT REPLICATE('String' + SPACE(3),6) AS Derived_String

Printing 5*5 Pattern

-- 5 * 5 
DECLARE @rows int = 5,@columns int = 5         
WHILE @rows > 0                 
BEGIN                          
PRINT REPLICATE('*'+SPACE(2), @columns)    
SET @rows = @rows - 1            
END

Printing 5*7 Pattern

-- 5 * 7 
DECLARE @rows int = 5, @columns int = 7              
WHILE @rows > 0                 
BEGIN                          
PRINT REPLICATE('*'+SPACE(2), @columns)    
SET @rows = @rows - 1            
END

Printing Diamond Pattern:

DECLARE @counter INT = 0,@maxid INT = 9,@space INT = 1
WHILE (@counter<@maxid)
BEGIN
PRINT SPACE((@maxid-@space)/2)+ REPLICATE('*',@space)
SET @counter = @counter + 1
IF(@counter<=(@maxid/2))
SET @space = @space+2
ELSE
SET @space = @space-2
END

Iterations for Diamond Pattern:

Iteration 1: 
@counter = 0 @space = 1 --> Prints 4 spaces and 1 * -->@counter = 1 <= 4  @space = 1 + 2 = 3 
Iteration 2:
@counter = 1 @space = 3 --> Prints 3 spaces and 3 * --> @counter = 2 <= 4  @space = 3 + 2 = 5
Iteration 3:
@counter = 2 @space = 5 --> Prints 2 spaces and 5 * --> @counter = 3 <= 4  @space = 5 + 2 = 7
Iteration 4:
@counter = 3 @space = 7 --> Prints 1 spaces and 7 * --> @counter = 4 <= 4  @space = 7 + 2 = 9
Iteration 5:
@counter = 4 @space = 9 --> Prints 0 spaces and 9 * --> @counter = 5 <= 4  @space = 9 - 2 = 7
Iteration 6:
@counter = 5 @space = 7 --> Prints 1 spaces and 7 * --> @counter = 6 <= 4  @space = 7 - 2 = 5
Iteration 7:
@counter = 6 @space = 5 --> Prints 2 spaces and 5 * --> @counter = 7 <= 4  @space = 5 - 2 = 3
Iteration 8:
@counter = 7 @space = 3 --> Prints 3 spaces and 3 * --> @counter = 8 <= 4  @space = 3 - 2 =1
Iteration 9:
@counter = 8 @space = 1 --> Prints 4 spaces and 1 * --> @counter = 9 <= 4  @space = 1-2 = -2



1 comment:

  1. Hi Bro,
    i need a pattern like double dimond plz help me, top one and down one one dimond

    ReplyDelete

  Printing Number Pattern using SQL Link for video answer: SQL: --********************* --PRINT Pattern --********************* -- 1 -- ...