C# program to print the Pascal Triangle

Here, we are going to learn how to print the Pascal Triangle?
Submitted by Nidhi, on September 22, 2020

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

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

Program:

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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.