Users Online

· Guests Online: 44

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

C# Program to Print Pascal Triangle

C# Program to Print Pascal Triangle

 

 

This is a C# Program to illustrate pascal triangle.

Problem Description

This C# Program Illustrates Pascal Triangle.

Problem Solution

Here This program uses the for loops to print Pascal’s triangle.

Program/Source Code

Here is source code of the C# Program to Illustrate Pascal Triangle. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.

/*
 * C# Program to Illustrate Pascal Triangle
 */
using System;
class Pascal
{
    public static void Main()
    {
        int[,] arr = new int[8, 8];
        Console.WriteLine("Pascal Triangle : ");
        for (int i = 0; i < 5; i++)
        {
            for (int k = 5; k > i; k--)
            {   
                Console.Write(" ");
            }
 
            for (int j = 0; j < i; j++)
            {
                if (j == 0 || i == j)
                {
                    arr[i, j] = 1;
                }
                else
                {
                    arr[i, j] = arr[i - 1, j] + arr[i - 1, j - 1];
                }
                Console.Write(arr[i, j] + " ");
            }
            Console.ReadLine();
        }
    }
}
Program Explanation

This C# program is used to display the pascal triangle. Pascal’s triangle is a triangular array of the binomial coefficients. The program consists of six integer type of variable, named ‘i’, ‘j’, ‘rows’, ‘array[][]’, ‘k’ and ‘num’. Out of these variable ‘i’, ‘j’ and ‘k’ have been defined to control the for loop, the integer ‘rows’ stores the limit of Pascal’s triangle entered by the user, it first asks for the value of limit of the triangle.

 

The program assigns ‘rows’ variable value with ‘i’ variable value, i.e., number of space with the limit of Pascal’s triangle, for loop in which ‘i’ is the loop control variable. Again, in order to control the space, a nested for loop with ‘k’ as a control variable is used.

Finally, for printing the elements, another nested for() loop of control variable ‘j’ has been used. The formula used to generate the numbers of Pascal’s triangle is:

 

array[i][j] = array[i – 1][j – 1] + array[i – 1][j]

After printing one complete row of numbers of Pascal’s triangle, the control comes out of the nested loops and goes to next line as commanded by ‘\n’ code. The process repeats till the control number specified is reached.

Runtime Test Cases
 
Pascal Triangle : 
    1
   1 1
  1 2 1
 1 3 3 1

 

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.65 seconds
10,855,141 unique visits