int main(int argc, char *argv[])
{
int n;
cout <<"enter number of rows ";
cin>>n;
const int N= n;
vector<vector<int>> matrix;
matrix.resize(N);
for (int i =0; i<N; ++i)
{
matrix[i].resize(N);
}
for (int rows=0; rows<N; rows++)
{
for (int col=0; col<=rows; col++)
{
if ((col = 0) || (col =rows))
{
matrix[rows][col] = 1;
}//end if
else
{
matrix[rows][col] = matrix[rows-1][col] + matrix[rows-1][col-1];
}//end else if
}//end for loop inside
}//end for loop traversing the rows
//print the triangle
for (int r = 0; r < N; r++)
{
for (int c=0; c<=r; c++)
{
cout << "\t"<< matrix[r][c];
}
cout <<endl;
}
system("pause");
return 0;
}
This is my code for pascal triangle. But when I run it, it gave me an error about vector subscript out of range. Please help me with this error. I spent too much time on it without an answer
First up please always use code tags, edit your post, select all the code, press the <> button on the format menu.
It makes your code easier to read, puts line numbers in. Also make sure it is indented.
As for your problem, is it these lines?
1 2 3 4 5
for (int col=0; col<=rows; col++)
// ........//
for (int c=0; c<=r; c++)
The standard idiom for a for loop is this:
for (int c = 0; c < r; c++){}
Arrays start at 0, and end at their size-1. Your code goes past the array boundary by one I suspect.