Given a number we have to print pascal triangle.
So what is Pascal triangle ?
Pascal Triangle is a triangle of triangular array of binomial coefficent.
Example:
input:5
output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Logic:
we will make 2d array as we see current value is sum of previous two values ,so we store previous value to array.
Code-
#include <bits/stdc++.h> using namespace std; int main() { int num; cout<<"enter rows of pascal "<<endl; cin>>num; ///lets print the pascal triangle. int pas[num][num]; for (int j=0; j<num; j++) //iterating lines { for (int i = 0; i <= j; i++) { if (j == i || i == 0) { pas[j][i] = 1; } else { pas[j][i] = pas[j-1][i - 1] + pas[j- 1][i]; } cout << pas[j][i] << " "; } cout<<endl; } }
Output:
enter no of row :5 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1
Time complexity:0(N*N)
Space Complexity:O(N*N)