Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C# Program to create Pascal’s Triangle
A Pascal’s triangle contains numbers in a triangular form where the edges of the triangle are the number 1 and a number inside the triangle is the sum of the 2 numbers directly above it.
A program that demonstrates the creation of the Pascal’s triangle is given as follows.
Example
using System;
namespace PascalTriangleDemo {
class Example {
public static void Main() {
int rows = 5, val = 1, blank, i, j;
Console.WriteLine("Pascal's triangle");
for(i = 0; i<rows; i++) {
for(blank = 1; blank <= rows-i; blank++)
Console.Write(" ");
for(j = 0; j <= i; j++) {
if (j == 0||i == 0)
val = 1;
else
val = val*(i-j+1)/j;
Console.Write(val + " ");
}
Console.WriteLine();
}
}
}
}
Output
The output of the above program is as follows.
Pascal's triangle 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1
Now, let us understand the above program.
The Pascal’s triangle is created using a nested for loop. The outer for loop situates the blanks required for the creation of a row in the triangle and the inner for loop specifies the values that are to be printed to create a Pascal’s triangle. The code snippet for this is given as follows.
for(i = 0; i<rows; i++) {
for(blank = 1; blank <= rows-i; blank++)
Console.Write(" ");
for(j = 0; j <= i; j++) {
if (j == 0||i == 0)
val = 1;
else
val = val*(i-j+1)/j;
Console.Write(val + " ");
}
Console.WriteLine();
}Advertisements