-9

Can any one tell me why I receive a System.IndexOutOfRangeException from this code?

char[,] matrix = new char[80, 18];
for (int i = 0; i < 80; i++)
    for (int j = 0; i < 18; j++)
        matrix[i, j] = '1';
disasterkid
  • 6,948
  • 25
  • 94
  • 179
  • 2
    thats what happens when you copy&paste the for loop without changing all the vars correctly. you missed the `i` in the 2nd loop. should have changed it to `j` as well – Banana Jan 15 '15 at 15:25
  • 5
    Thats't reason why we always say: _Use the debugger first_ – Soner Gönül Jan 15 '15 at 15:25
  • 1
    Also duplicate: [What is an “index out of range” exception, and how do I fix it?](http://stackoverflow.com/questions/24812679/what-is-an-index-out-of-range-exception-and-how-do-i-fix-it) – Soner Gönül Jan 15 '15 at 15:27

3 Answers3

11

You are checking if i is smaller than 18 in the second for loop

char[,] matrix = new char[80, 18];
for (int i = 0; i < 80; i++)
    for (int j = 0; i < 18; j++) //<-- Right there.
        matrix[i, j] = '1';

Change to:

char[,] matrix = new char[80, 18];
for (int i = 0; i < 80; i++)
    for (int j = 0; j < 18; j++) //<-- Right there.
        matrix[i, j] = '1';
0xDEADC0DE
  • 2,453
  • 1
  • 17
  • 22
4

Problem : in your second for loop you are checking with variable i instead of j

for (int i = 0; i < 80; i++)
for (int j = 0; i < 18; j++)
               ^^^ should be j

Try This:

for (int i = 0; i < 80; i++)
for (int j = 0; j < 18; j++)
Sudhakar Tillapudi
  • 25,935
  • 5
  • 37
  • 67
3

...because you have a typo in for (int j = 0; i < 18; j++)

Yury Rumega
  • 220
  • 1
  • 12