vector subscript out of range pascal triangle

#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <vector>

using namespace std;

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
Hi,

Welcome to cplusplus :+)

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.

Hope all goes well :+)
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <vector>

using namespace std;

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;
}
i make terrible rookie mistakes. This line is wrong if ((col = 0) || (col =rows))

it should be if ((col==0)||(col==rows))

haizz. i hate debugging
Last edited on
Topic archived. No new replies allowed.