Friday 30 January 2015

Number Pattern in C# - 16

Question: Program to print the following pattern?


           1
          2 1 2
       3 2 1 2 3
    4 3 2 1 2 3 4
 5 4 3 2 1 2 3 4 5
    4 3 2 1 2 3 4
       3 2 1 2 3
          2 1 2
             1


Code Snippet:


  1. using System;  
  2. public class Pattern  
  3. {  
  4.     public static void Main()  
  5.     {  
  6.         int row, col, n, temp;  
  7.   
  8.         Console.Write("Enter the no. of row: ");  
  9.         n = Convert.ToInt32(Console.ReadLine());  
  10.   
  11.         temp = n;  
  12.   
  13.         for(row=1; row<=n; row++)  
  14.         {  
  15.             for(col = 1; col<temp; col++)  
  16.             Console.Write("  ");  
  17.             temp--;  
  18.   
  19.             for(col = row; col >=1; col--)  
  20.             Console.Write("{0} ",col);  
  21.       
  22.             for(col = 2; col<=row; col++)  
  23.             Console.Write("{0} ",col);  
  24.   
  25.             Console.WriteLine();  
  26.         }  
  27.   
  28.         for(row = 1; row<=n; row++)  
  29.         {  
  30.             for(col = 1; col <= row; col++)  
  31.             Console.Write("  ");  
  32.   
  33.             for(col = n-row; col >=1; col--)  
  34.             Console.Write("{0} ", col);  
  35.   
  36.             for(col = 2; col<=n-row; col++)  
  37.             Console.Write("{0} ", col);  
  38.   
  39.             Console.WriteLine();  
  40.         }  
  41.   
  42.         Console.ReadLine();  
  43.     }  
  44. }  


Output of numberpattern
Fig: Screenshot of output