0

why error?

static void Main(string[] args) { int[ ] a = new int[10]; for (int k = 5; k < 12; k++) { a[k] = k*2; } for (int x = 0; x < 10; x++) { Console.WriteLine(a[x]); } }

2nd Oct 2017, 2:33 AM
William
8 Answers
+ 6
Your array only contains 10 elements, from 0 - 9, your first for loop tried to assign a value to an element that doesn't exist, because the loop was designed to start from 5 - 11. Hth, cmiiw
2nd Oct 2017, 2:38 AM
Ipang
+ 3
@William, your loop can start from any number, but in your first loop case, when k is incremented to 10 that's when error happens, your array only has elements from index 0 - 9, there's no 10th and 11th element. Hth, cmiiw
2nd Oct 2017, 8:01 AM
Ipang
+ 3
This is your array (a) of ten elements. ----------------------------------------------- Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | ---------------------------------------------- Value | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | ----------------------------------------------- ^ ^ ^ ^ ^ # # Then you use for loop to assign values to array elements, starting from index 5 until 11. for(int k = 5;k < 12;k++) The loop succeeded to assign values to elements from a[5] until a[9] (marked by ^), but the loop didn't stop there, it continued to try assigning values to a[10] and a[11] (marked by #) which failed, because array (a) only had ten elements, with index from 0-9. P.S. Your most recent changed code will work just fine. Hth, cmiiw
2nd Oct 2017, 9:26 PM
Ipang
+ 1
its a rule of arrays to start at 0, like a list the first number is the first, not the fifth.
2nd Oct 2017, 7:34 AM
Raran Costa
Raran Costa - avatar
0
thanks. but why it cannot start from 5? why it must start from 0? then how i can create a array with first number is 10?
2nd Oct 2017, 7:15 AM
William
0
the index should start from 0, but the value could from any number. I just don't know how make it start from numbers not equal to 0.
2nd Oct 2017, 2:17 PM
William
0
i find the answer. maybe it's because of [k].it make k play double roles. 1: index; 2: help to create element value. so if i want to create an array start from other numbers, maybe i should declare another int besides k.
2nd Oct 2017, 2:24 PM
William
0
i find the answer. maybe it's because of [k].it make k play double roles. 1: index; 2: help to create element value. so if i want to create an array start from other numbers, maybe i should declare another int besides k. or like below. static void Main(string[] args) { int[ ] a = new int[10]; for (int k = 0; k < 10; k++) { a[k] = k*2+10; } for (int x = 0; x < 10; x++) { Console.WriteLine(a[x]); } }
2nd Oct 2017, 2:27 PM
William