Why is the output like that? | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
0

Why is the output like that?

Why does int[ ] arr = {2, 4, 7}; for(int k=0; k<arr.Length; k++) { Console.WriteLine(arr[k]); } output 2,4,7 when k is never given the actual value f.e 2

11th Dec 2019, 10:41 AM
Simon Hahner
Simon Hahner - avatar
1 Réponse
+ 4
An array is a data structure which content can be accessed by index. The first element of an array is always indexed as 0, and so on. As you have declared an array (int[] arr = {2, 4, 7};) of 3 elements, to get the first one you use 0 as an index (arr[0]) and you get the first element (2). Your for loop gives k the values 0, 1 and 2, so your code prints the whole array, index by index Console.WriteLine(arr[0]); // 2 Console.WriteLine(arr[1]); // 4 Console.WriteLine(arr[2]); // 7
11th Dec 2019, 10:51 AM
Deroman
Deroman - avatar