Software & Finance

 

 







C# Pascal Triangle


 

I have given here C# code to build a pascal triangle. It uses simple nested for loops and Console.WriteLine functions. The input would be the number of rows in the pascal triangle.

 

 

Source Code


using System;

using System.Collections.Generic;

using System.Text;

 

namespace PascalTriangle

{

   class PascalTriangle

   {

      static void Main(string[] args)

      {

 

         System.Console.WriteLine("Pascal Triangle Program");

         System.Console.Write("Enter the number of rows: ");

         string input = System.Console.ReadLine();

 

         int n = Convert.ToInt32(input);

        

 

         for (int y = 0; y < n; y++)

         {

            int c = 1;

            for (int q = 0; q < n - y; q++)

            {

               System.Console.Write("   ");

            }

 

            for (int x = 0; x <= y; x++)

            {

               System.Console.Write("   {0:D} ", c);

               c = c * (y - x) / (x + 1);

            }

            System.Console.WriteLine();

            System.Console.WriteLine();

         }

         System.Console.WriteLine();

      }

   }

}

Output


 

 




If you have any questions, you can chat with me online through facebook by making me as your friend.


FREE Subscription: Like us on facebook to receive updates on C, C++, C#, Java, PHP, ASP.NET, XAML, WPF and Silverlight.