Beginning C# - Part 13: For Loops | Ray Wenderlich

In this episode, you'll be introduced to your first loop, learn how to use it, and see why it's so powerful when combined with arrays.


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/3247-beginning-c/lessons/13
1 Like

Hey Brian,
I have a question.
At 12:30 u typed players[i] and scores[i].
Why did u typed the two iโ€™s.
I dont get why u have to do that, i get a error if i dont, but i dont get it why i have to do it.
Can u maybe explain why u have to do that, to me?

Greetings, meee :stuck_out_tongue:

1 Like

Hi pepper,

players and scores are both arrays and each one must be accessed with an index. In this case you are using the same index of i because the 2 arrays are linked.

Hi Brian,

could you explain this line of code to me please?

for (int i = 0; i < score.Length; i++) {
_ Debug.Log("The " + i + "element is " + score[i]);_
}

i have read your reply to the question above, however i still do not understand the purpose of the โ€œiโ€ in score[i]

Also can you explain what the part score.Length is referring too please?

sorry if these are very basic questions, i just cant proceed until i fully understand each part xD

Thanks!

Mark

1 Like

Hi Mark,

Do you understand how arrays are accessed? Arrays are a collection of data that are accessed by using an index value. Letโ€™s say you have an array of 3 ints. The first element in the array is accessed by array[0] and the third element by array[2]. The command array.Length returns the number of elements in the array, 3 in my example.

What the code you referenced does is set up a loop that will display each score in the score array. The loop counts from 0 to (score.Length -1) (remember that array indexes start at 0). i is the index the for loop uses to control the loop. It is also used as the index into the score array. So, when i = 0, score[0] gets printed to the Debug.Log. The next time through the loop i = 1 accessing score[1] and so on until the value of i is equal to the number of elements in the score array at which point the for loop terminates (i < score.Length).

Yes, these are basic questions but asking them is necessary to understand these basic concepts of programming so keep asking. :slight_smile:

1 Like

Hi Brian,

Thanks for the great explanation, I understand it a lot better now.

โ€œiโ€ is the index to access our arrays and โ€œarray.Lengthโ€ is the number of elements in the array.

So if I wanted to access say players[1] and score[2] i would have to use 2 separate indexes?

Thanks for the swift reply! These tutorials are amazing for beginners like myself :slight_smile: :+1:

1 Like

Sorry for the delay in responding Mark. To answer your question, you would either have to use 2 separate indices or use one index with some kind of math adjustment to access a different element of the array. In your example you could use players[i] (assumes i = 1) and score[i+1].