C# program to print the Pascal Triangle

Here, we are going to learn how to print the Pascal Triangle? By Nidhi Last updated : April 15, 2023

Pascal Triangle

A Pascal Triangle is a triangle of numbers where each number is the two numbers directly above it added together in the previous row.

Here we will Pascal Triangle using for loop on the console screen.

C# code for print the Pascal Triangle

The source code to print the Pascal Triangle is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to print Pascal Triangle

using System;
class PascalTringle
{

    public static void Main()
    {
        int [,]arr      ;
        int rows    = 0 ;
        int loop1   = 0 ;
        int loop2   = 0 ;
        int space   = 0 ;

         arr = new int[8, 8];

        Console.Write("Enter the total number of rows to draw Pascal Triangle : ");
        rows = int.Parse(Console.ReadLine());


        for (loop1 = 0; loop1 < rows; loop1++)
        {
            for (space = rows; space > loop1; space--)
            {
                Console.Write(" ");
            }

            for (loop2 = 0; loop2 < loop1; loop2++)
            {
                if (loop2 == 0 || loop1 == loop2)
                {
                    arr[loop1, loop2] = 1;
                }
                else
                {
                    arr[loop1, loop2] = arr[loop1 - 1, loop2] + arr[loop1 - 1, loop2 - 1];
                }
                Console.Write(arr[loop1, loop2] + " ");
            }
            Console.WriteLine();
        }
    }
}

Output

Enter the total number of rows to draw Pascal Triangle: 5

    1
   1 1
  1 2 1
 1 3 3 1
Press any key to continue . . .

Explanation

Here, we create a class PascalTriangle that contains the Main() method. The Main() method is the entry point for the program. Here we read the value of the total number of rows from the user. Then we use a nested loop to print Pascal Triangle on the console screen.

C# Basic Programs »


Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.