Printing Number Pattern using SQL
Link for video answer:
SQL:
--*********************
--PRINT Pattern
--*********************
-- 1
-- 11
-- 111
-- 1111
-- 11111
-- 22222
-- 2222
-- 222
-- 22
-- 2
-- Solution:
DECLARE @counter int = 1 -- Declare and Initialize counter
DECLARE @number int = 1 -- Declare and Initialize number to be printed
WHILE @counter <= 5 -- Condition
BEGIN -- Begin
IF(@number = 1)
BEGIN
PRINT replicate(@number , @counter) -- Print
SET @counter = @counter + 1
IF(@number =1 AND @counter=6) -- once @var value becomes 6 on 5th iteration we increment the number just once
BEGIN
SET @number=@number+1
PRINT replicate(@number , @counter-1)
SET @counter = @counter - 2
END
END
ELSE
BEGIN
PRINT replicate(@number , @counter)
SET @counter = @counter - 1 -- decreasing the counter and using the incremented number from above
IF(@counter=0)
BREAK;
END
END
2nd Way:
DECLARE @counter int = 1 -- Declare and Initialize counter
DECLARE @number int = 1 -- Declare and Initialize number to be printed
WHILE @counter <= 5 -- Condition
BEGIN -- Begin
IF(@number = 1)
BEGIN
PRINT replicate(CAST(@number AS VARCHAR(2)) + SPACE(5), @counter)
PRINT('')
SET @counter = @counter + 1
IF(@number =1 AND @counter=6) -- once @var value becomes 6 on 5th iteration we increment the number just once
BEGIN
SET @number=@number+1
PRINT replicate(CAST(@number AS VARCHAR(2)) + SPACE(5), @counter-1)
PRINT('')
SET @counter = @counter - 2
END
END
ELSE
BEGIN
PRINT replicate(CAST(@number AS VARCHAR(2)) + SPACE(5), @counter)
PRINT('')
SET @counter = @counter - 1 -- decreasing the counter and using the incremented number from above
IF(@counter=0)
BREAK;
END
END
3rd Way:
DECLARE @counter1 int = 1 -- Declare and Initialize counter
DECLARE @number1 int = 1 -- Declare and Initialize number to be printed
WHILE @counter1 <= 5 -- Condition
BEGIN -- Begin
IF(@number1 = 1)
BEGIN
PRINT replicate(@number1, @counter1) -- Print
SET @counter1 = @counter1 + 1
END
END
SET @number1 = 2
SET @counter1 = 5
WHILE @counter1 <= 5
BEGIN
PRINT replicate(@number1 , @counter1) -- Print
SET @counter1 = @counter1 - 1
IF(@counter1=0)
BREAK;
END