Saturday 31 January 2015

Number Pattern in C# - 17

Question: Program to print the following pattern?


          1
         1 2 1
      1 2 3 2 1
   1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1
   1 2 3 4 3 2 1
      1 2 3 2 1
         1 2 1
            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.         temp =n;  
  11.   
  12.         for(row = 1; row <=n; row++)  
  13.         {  
  14.             for(col = 1; col <temp; col++)  
  15.             Console.Write("  ");  
  16.             temp--;  
  17.   
  18.             for(col = 1; col < row; col++)  
  19.             Console.Write("{0} ", col);  
  20.   
  21.             for(col= row; col>=1; col--)  
  22.             Console.Write("{0} ", col);  
  23.               
  24.             Console.WriteLine();  
  25.         }  
  26.   
  27.         for(row = 1; row<=n; row++)  
  28.         {  
  29.             for(col = 1; col<=row; col++)  
  30.             Console.Write("  ");  
  31.   
  32.             for(col = 1; col<=n-row; col++)  
  33.             Console.Write("{0} ", col);  
  34.   
  35.             for(col = n-row-1; col>=1; col--)  
  36.             Console.Write("{0} ", col);  
  37.   
  38.             Console.WriteLine();  
  39.         }  
  40.   
  41.             Console.ReadLine();  
  42.     }  
  43. }  


Output of pattern programming
Fig: Screenshot of Output