Matrix cannot read last element in double array

I run simple matrix ,however when i increased the size of matrix, for example 3x3, the element in 3x3 cannot be read ,it happen also when i try 4x4,it seems that when i=j they become 0

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
53
54
#include <fstream>
#include <iostream>
#include <iomanip>


#define M 4

using namespace std;

void main()
{
	int i, j;
	double G[M+1][M+1] ;

	G[1][1] = 3;
	G[1][2] = 6;
	G[1][3] = -8;
	G[1][4] = 11;

	G[2][1] = 0;
	G[2][2] = 0;
	G[2][3] = 9;
	G[2][4] = 3;

	G[3][1] = 6;
	G[3][2] = 4;
	G[3][3] = 10;
	G[3][4] = 9;

	G[4][1] = 16;
	G[4][2] = 0;
	G[4][3] = 0;
	G[4][4] = 1;

	for (i = 1; i <= M; i++)
	for (j = 1; j <= M; j++)
	G[M][M] = 0;
	
	cout <<"Matrix A:" <<endl;

	for (i=1;i<= M;i++)
	{
		for (j=1;j<=M;j++)
		{
			cout << setw(7) << G[i][j] << "    ";
		}
        cout << endl;
	}
	cin.get();




}
What is the purpose of lines 35 to 37? That is setting the last row and column of the array to zeros.

Note that subscripts start from 0, not 1, so this line
 
double G[M+1][M+1] ;
is defining a 5 x 5 array.

The first row/column are never used, and the last row/column are all set to zero.

By the way, void main() is not valid C++, a standards-conforming compiler will reject it. It should always be int main().
Why are you trying to force C++ to use a 1 based array? Arrays in C or C++ start at zero and end at size - 1, you really really should get used to this way of dealing with arrays.

What is the point of lines 35 through 37?
many Thanks!it work,i just copied the code from a book and try to play around with the array.thanks for the explanation,i will note for future use:).
Topic archived. No new replies allowed.