Find the Nth row in Pascal’s Triangle in C++
Nth row of Pascal’s Triangle in C++
Here, in this page we will discuss the program to find Nth row of pascal’s triangle in C++ Programming language. We are given with a non-negative integer and we need to print the Nth row. We are assuming zero based starting of the rows.
Pascal Triangle :
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Example : N=2
- Output : 1 2 1
Method 1 (Using recursion):
- Create a recursive function say getRow(int index).
- Declare a vector say cur_row
- Now, as the 1-st element of every row is 1 so, push 1 in cur_row vector.
- Check if index == 0, then return cur_row.
- Create a vector to hold the previous row, say prev and set prev = getRow(index-1)
- Run a loop from [1, prev.size())
- Take variable say curr = prev[i-1] + prev[i]
- and push it to cur_row
- As the last element of every row is 1 so again push 1 to cur_row vector.
- And return cur_row
Code to find Nth row of Pascal's Triangle in C++
#include <bits/stdc++.h> using namespace std; //Recursive Function vector<int> getRow(int index) { vector<int> cur_row; // 1st element of every row is 1 cur_row.push_back(1); if (index == 0) { return cur_row; } vector<int> prev = getRow(index - 1); for(int i = 1; i < prev.size(); i++) { int curr = prev[i - 1] + prev[i]; cur_row.push_back(curr); } cur_row.push_back(1); return cur_row; } // Driver Code int main() { int n = 2; vector<int> arr = getRow(n); for(int i = 0; i < arr.size(); i++) { if (i == arr.size() - 1) cout << arr[i]; else cout << arr[i] << " "; } return 0; }
Output :
1 2 1
Method 2 :
In this method we will discuss the efficient way to find the Nth row of the triangle.
- Nth row = nC 0 nC1 nC2 … nCn
- So, by using the above concept to find the nth row.
- nCr = (nCr-1 * (n – r + 1))/r
- Take a variable say prev=1 (as, nC0=1)and print prev.
- Now, Run a loop from [1, N], take a variable say curr, and set curr = (prev * (N – i + 1)) / i;
- And, Print Curr.
Code in C++
#include <bits/stdc++.h> using namespace std; //Function to print N-th row void getrow(int N) { int prev = 1; cout << prev; for (int i = 1; i <= N; i++) { int curr = (prev * (N - i + 1)) / i; cout << " " << curr; prev = curr; } } // Driver Program int main() { int N = 2; getrow(N); return 0; }
Output :
1 2 1
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Login/Signup to comment