The issue with your C++ program lies in the printPascal function. Although you correctly generate each row of Pascal's Triangle and store it in the arr vector, you never actually add this arr to the mat vector, which is supposed to store all the rows. As a result, mat remains empty, and when you try to iterate over it in the main function, no output is produced.
Here’s a detailed breakdown of the problem and the solution:
Problem: Missing mat.push_back(arr);
In the printPascal function, after constructing each row (arr) of Pascal's Triangle, you need to add this row to the mat vector. Without this step, mat remains empty, and thus, the main function has nothing to iterate over and display.
Corrected Code
Add the line mat.push_back(arr); after the inner loop that constructs each row. This ensures that each row is stored in mat.
// Cpp program for Pascal's Triangle using Binomial
// Coefficient in O(n^3) and O(1) Space
#include <iostream>
#include <vector>
using namespace std;
int binomialCoeff(int n, int k) {
int res = 1;
if (k > n - k)
k = n - k;
for (int i = 0; i < k; ++i) {
res *= (n - i);
res /= (i + 1);
}
return res;
}
// Function to print first n rows
// of Pascal's Triangle
vector<vector<int>> printPascal(int n) {
// Iterate through every row and
// store entries in it
vector<vector<int>> mat;
for (int row = 0; row < n; row++) {
// Every row has number of
// integers equal to row
// number
vector<int> arr;
for (int i = 0; i <= row; i++)
arr.push_back(binomialCoeff(row, i));
// Add the current row to the matrix
mat.push_back(arr);
}
return mat;
}
int main() {
int n = 5;
vector<vector<int>> mat = printPascal(n);
for (int i = 0; i < mat.size(); i++) {
for(int j = 0; j < mat[i].size(); j++) { // Use mat[i].size() instead of mat[0].size()
cout << mat[i][j] << " ";
}
cout << endl;
}
return 0;
}
Additional Improvements
-
Accessing the Correct Row Size:
In the main function, you should use mat[i].size() instead of mat[0].size() when iterating through each row. This allows your program to handle rows of varying lengths correctly.
-
Formatting the Output:
Adding a space (" ") after each number makes the output more readable.
Expected Output
When you run the corrected program with n = 5, you should get the following output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Summary
The primary reason your program wasn't returning any output is that the mat vector never got populated with the rows of Pascal's Triangle. By adding mat.push_back(arr); after constructing each row, you ensure that mat contains all the necessary data for the main function to display.
Because the printPascal function never adds each row to mat, the returned mat is empty and nothing is printed. To fix this, you should add mat.push_back(arr); after filling each row in printPascal.