# Thread: Why does my iteration to fill a matrix, fill another non-related matrix as well?

1. ## Why does my iteration to fill a matrix, fill another non-related matrix as well?

Hi,

I just started programming in C++, so I wonder if I just have messy programming, or that this is something wierd. My problem is the following:
I have to fill a matrix with numbers (normally with random numbers, but for the example I just fill them fill the iteration variable, see code below). After some weird results farther down the code, I noticed that the numbers I filled the matrix with, also showed up in another non-related variable.
I started to play around with that, and the wierd thing is, that if I declare a new variable after the variable that was filled up first, that new variable gets filled instead of the previous one.
In the code below I fill 3 three variables (each a 1 dimension matrix) with the number 12 for every element.
Then I fill a 2 dimensional matrix with different numbers.
The last (in order of declaration) 1 dimensional matrix takes over values which should only be in the 2 dimensional matrix.

I do not know what is happening here. I use the bloodshed dev c++ compiler.

Any suggestions are greatly appreciated. I think can ignore the problem by declaring an extra 1 dimension matrix that I will never use, but still it feels like there is something happening I don't know.

Here's the code:
Code:
```#include <iostream>
#include <stdio.h>
#include <cmath>
#include <sstream>
#include <string>

using namespace std;

int main()
{

int maxalleles=10;
double freq[maxalleles], margw[maxalleles], mutant[maxalleles];
double w[maxalleles][maxalleles];
for (int i=1; i<=maxalleles; ++i){
freq[i]=12;
margw[i]=12;
mutant[i]=12;
for (int j=1; j<=maxalleles; ++j){
w[i][j]=i;
w[j][i]=w[i][j];//mirror the matrix, nessecary for calculations furtheron, but not in this code.
}
}

for (int i=1; i<=maxalleles; ++i){
cout<<"allele "<<i<<" = "<<freq[i]<<"\n";
cout<< "margw "<<i<<" = "<<margw[i]<<"\n";
cout<<"mutant "<<i<<" = "<<mutant[i]<<"\n";
for (int j=1; j<=maxalleles; ++j){
cout<<"matrix "<<i<<" "<<j<<" ="<<w[i][j]<<"\n";

}
}

cin.get();

}```

2. Originally Posted by NinchN
Hi,

I just started programming in C++,
Code:
```#include <iostream>
#include <stdio.h>
#include <cmath>
#include <sstream>
#include <string>

using namespace std;

int main()
{

int maxalleles=10;
double freq[maxalleles], margw[maxalleles], mutant[maxalleles];
double w[maxalleles][maxalleles];
for (int i=1; i<=maxalleles; ++i){```
For array dimensions equal to 10, the subscripts go from 0 to 9:

Code:
`    for (int i = 0; i < maxalleles; ++i){`
Regards,

Dave

3. Arrays are zero-based in C and C++; you're starting from index 1 and going to index 10; index 10 is beyond the array bounds because you've allocated arrays with 10 elements (indices 0-9).

4. He Messy coding indeed, thnx, works fine now.