Write a C++ Program to Print Pascal Triangle with an example. In this Pascal triangle example, long factorialNum(int number) finds the factorial of a number. Within the nested for loop, we used this method to get our pattern.
#include<iostream>
using namespace std;
long factorialNum(int number)
{
long factorial = 1;
for (int i = 1; i <= number; i++)
{
factorial = factorial * i;
}
return factorial;
}
int main()
{
int i, j, number;
cout << "\nPlease Enter the Number = ";
cin >> number;
cout << "\n----------\n ";
for (i = 0; i < number; i++)
{
for (j = 0; j <= (number - i - 2); j++)
{
cout << " ";
}
for (j = 0; j <= i; j++)
{
cout << factorialNum(i) / (factorialNum(j) * factorialNum(i - j)) << " ";
}
cout << "\n";
}
return 0;
}
Please Enter the Number = 7
----------
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
We are using the Recursion concept to Print the Pascal Triangle. Please refer to the C++ program.
#include<iostream>
using namespace std;
long factorialNum(int number)
{
if(number == 0 || number == 1)
{
return 1;
}
else
{
return number * factorialNum(number - 1);
}
}
int main()
{
int i, j, number;
cout << "\nPlease Enter the Number for Pascal Triangle = ";
cin >> number;
cout << "\n-----Pascal Triangle-----\n ";
for (i = 0; i < number; i++)
{
for (j = 0; j <= (number - i - 2); j++)
{
cout << " ";
}
for (j = 0; j <= i; j++)
{
cout << factorialNum(i) / (factorialNum(j) * factorialNum(i - j)) << " ";
}
cout << "\n";
}
return 0;
}
