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 } } } }
3 odpowiedzi
+ 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
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?
0
Brilliant, thanks so much for you help both of you :)