What is it and how does it repeat in C #?

6
for (int i = 0; i < palavra.Length; i++)

What does each word mean? And how does each part of this code work?

    
asked by anonymous 15.09.2017 / 13:04

1 answer

14

This is the beginning of a repeat loop with a start, a condition indicating the end of the loop, and a step that should be performed in each interaction.

for ()

It is the keyword that tells the compiler that it is a loopback in this format described above. It will necessarily have the 3 parts in parentheses

int i = 0;

Here I imagine that you already know, you are declaring an integer variable called i and assigning 0 to it. This occurs only once at the beginning. This variable will only exist inside the block of for .

i < palavra.Length;

Here is the condition, just put it in a if . As long as this expression results in true the loop will continue executing its block of code in successive repetitions. In the case the condition checks whether i is less than the size of the palavra variable that must be a collection of data (array), or List , or string , most likely, or something like this). When you hit the value of it with the size, it means that you went through all data collection.

i++

Here you are incrementing by 1 the variable i , which is the most common action of a for , always walk 1 in 1, but you can use any action that makes sense there. Then in each step of the loop the variable will have its value changed with the next unit. Probably within it the variable will be used to access the specific element of the data collection. The scan will be complete since it starts at 0 and ends at its size.

Read more:

15.09.2017 / 13:22