Q:

C# program to print the Pascal Triangle

belongs to collection: C# Basic Programs | basics

0

C# program to print the Pascal Triangle

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# Basic Programs | basics

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C# program to calculate the sum of two binary numb... >>
<< C# program to calculate the traveled distance base...