Regarding Arrays | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
0

Regarding Arrays

Can someone please explain how these are not giving the same results, Thanks using System; namespace ArrayandStringPractice { class MainClass { public static void Main(string[] args) { int[] myThirdArray = new int[5] { 1, 5, 3, 6, 8 }; int sum = 0; for (int j = 0; j < myThirdArray.Length; j++) { sum+= j; Console.WriteLine(sum); //Output is 10 } int[] myFourthArray = new int[5] { 1, 5, 3, 6, 8 }; int sum1 = 0; foreach (int j in myFourthArray) { sum1 += j; Console.WriteLine(sum1); //Output is 23 } } } }

6th Jul 2017, 11:22 AM
eric
3 Réponses
+ 2
for (int j = 0; j < myThirdArray.Length; j++) { sum+= j; Console.WriteLine(sum); //Output is 10 } Here, j is only the index of array, not the values, so 0+1+2+3+4 = 10 where, foreach (int j in myFourthArray) { sum1 += j; Console.WriteLine(sum1); //Output is 23 } in this case j is actually the numbers inside the array, so 1+5+3+6+8 = 23
6th Jul 2017, 11:31 AM
Salekin
Salekin - avatar
0
aH OK I see. So is this a general rule that the For Loop will deal with the Index and Foeach will deal with the number inside the Array? I mean how would i make the first part deal with the number inside the array and not the Index?
6th Jul 2017, 11:35 AM
eric
0
Brilliant, thanks so much for you help both of you :)
6th Jul 2017, 11:39 AM
eric