0

C# Simple question about arrays

C# code: int[ ] a = new int[10]; for (int k = 1; k <= 10; k++) { a[k] = k*2; } for (int k = 0; k < 10; k++) { Console.WriteLine(a[k]); } Why do I still get 0 as the output of the first value? From the first for loop I declared k's value as 1 and should be rendering 2...20 instead it shows 0...18 It gives an error of "out of bounds". if I change the first loops condition to <= 9. it still gives me 0 as the initial value and stops at 18 update: so it seems 0 could be a default value given to the "0" position. I would imagine that it would be the last/10th position that would be set with the value of 0. But theres still the question, why doesnt k <= 10 work?

7th Feb 2018, 12:21 AM
kideoh0jima
6 Antworten
+ 8
When you declare int[] a = new int[10]; You declare an integer array of size 10. The valid indexes of this array would be 0 1 2 3 4 5 6 7 8 9 i.e. 10 indexes which starts from 0 and ends with 9. Go figure.
7th Feb 2018, 2:11 AM
Hatsy Rei
Hatsy Rei - avatar
+ 1
make last line, console.writeline(a[k+1])<<easy way, not only way. and 0-10 wont fit in your array only 0-9 so new arr[11] if you want it to hold 0-10.
7th Feb 2018, 1:17 AM
emmey
emmey - avatar
+ 1
@emmey I made k = 1 so it can only declare 1-10: (1*2 = 2 = k),(2*2 = 4 = k), etc., instead of 0-10, ie excluding 0 * 2. what im trying to do is output all even natural numbers ie 2-20. I think the last line works fine. the first for loop is the one giving an error thanks for answering
7th Feb 2018, 1:33 AM
kideoh0jima
+ 1
int[ ] a = new int[11]; for (int k = 1; k <= 10; k++) { a[k] = k*2; Console.WriteLine(a[k]); works for that without the second loop.
7th Feb 2018, 1:40 AM
emmey
emmey - avatar
+ 1
@Hatsy Rei yeah I get it now. I thought a[k] = k*2; was "enumerating" the values in the array, like: new int[10] {k}; I actually needed to add another operation to get the desired result: a[k] = (k+1)*2; so in actuality it means: (k+1)*2 = value is set/index it to a[0,1,2...9] "position" sololearn never really explained it. maybe, yet.
7th Feb 2018, 3:08 AM
kideoh0jima
0
c# code int[ ] arr = new int[7]; for(int k=0;k<7 ;k++) { Console.WriteLine(array[k]); }
7th Feb 2018, 5:09 PM
Mesut Alcicek
Mesut Alcicek - avatar