Why it doesnt output 9 outputs? | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
+ 2

Why it doesnt output 9 outputs?

class Program { static void Main(string[] args) { int[] b = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; for (int k = 1; k <= b.Length; k++) { b[k] = k*k; Console.WriteLine(b[k]); } } }

17th Sep 2018, 5:56 PM
Shaitzu15
Shaitzu15 - avatar
4 Antworten
+ 5
I think it's because you have to change the limits in the loop. First index in the array is 0, so k = 0. The last index in the loop is b.Length - 1 so k = b.Length - 1.
17th Sep 2018, 6:11 PM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
+ 4
simply change b[k] into b[k-1] and it will work. b[k-1]=k*k; Console.WriteLine(b[k-1]);
17th Sep 2018, 6:32 PM
voja
voja - avatar
+ 3
D⚽⚽⚽⚽7⃣7⃣7⃣ yeah, agree. the problem is b[k] =k*k because in last iteration k will be 9 and b[9] will show an error. There's 8 indices (indexes).
17th Sep 2018, 6:23 PM
voja
voja - avatar
+ 2
The indices are 9, because in the array start counting at 0, so when we reach 8 => we have 9 elements. The problem is the last calculation because the last element is b[8], not b[9] => out of array bounds.
17th Sep 2018, 6:28 PM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar