Understanding the for cycle


When we create a for cycle in any language, sometimes we do not understand the lines and variables that we develop and why we created them.


When we create a start variable (example i ) on we understand that it is the clue (better known as index ) of an array or object.

for (let i = 0; i < length; i++) //here your code loop

When we make this sentence (most of the programmers and I include myself) we do not understand.


Why is the sign < in our loop? What logic represents that the variable índice is smaller than the number of times to be repeated?

asked by Merling Samuel Sobalvarro 12.02.2018 в 23:16

4 answers


The for cycle is basically an iterative structure to execute the same code segment a desired number of times, this desired number of times is controlled by a condition that will evaluate whether or not it continues executing the internal code lines. The basic parts are

for (inicialización; condición; incremento) //here your code loop
  • The initialization serves as the basis or beginning of the cycle, ie for example if you want to execute 20 lines of code in a for , you could have many options, I would say infinite variations.

    for (let i = 0; i < 20; i++) { ... }
    for (let i = 10; i < 30; i++) { ...}
  • The two forms will work. but mostly the initial variable of the cycle for is used in 0, this is so that apart from serving as variable iteradora also works as indice to reference fixes positions and since they start from 0. It is customary to start in 0 . Beware that you can initialize more than one variable in this part.

  • The second part is the condition, the essential part of the cycle, in this part it will be evaluated if the cycle continues or not. It could be understood as a if if the result is true then it continues executing and if it is false it leaves the cycle. In this part you can have different types of comparison and more than one condition always following closely the logical tables of truth.
  • Mostly as in the initialization, the length is placed, that is, the number of times you want the code to be executed or the length of the array to avoid getting an exception of type IndexOfRange when used as an index. But it could simply be a variable booleana and act the same way. (ejm)

    // se ejecutará 5 veces ya que cuando i=5, cambiará la bandera
    // y la condición será false y saldrá del for
    let isNext= true;
    for (let i = 0; isNext; i++) { 
        if(i==5) isNext = false;
        else console.log(i)

    This second part always must return a value booleano , true or false

  • The increment is mostly used to change the state of the iterator variable, there are also different variations and as in the initialization, it can contain more than 1 variable incremented, in addition to increase it can also be decremented. these two can be 1 in 1 (++) or (-) or whatever you want i+=2 (2 in 2) i-=2 (2 in 2) em> descending. You have to have some clear things in this part, for this maybe you can serve this question (ejm)

    //Se ejecutará 10 veces , pero se hace de forma descendente el conteo.
    for (var i = 10; i >0; i--) { ...}
    // se ejecutará 5 veces dado que hace el decremento de 2 en 2
    for (var i = 10; i >0; i-=2) { ...}
  • answered by 13.02.2018 / 00:36

    Normally the expression you see in that cycle for is used to traverse the arrays, which does not mean that it is only used for that.

    This is because you have to remember that arrays start at position 0 .

    Therefore, if we have a i=0 index and we have three elements in our array, if we do the following: i <= length would give us a ArrayIndexOutOfBoundsException in Java for example, since it would try to access the element array[3] which does not exist, in case we want to obtain its value.

    In any case, the condition that is used in the cycle for must always conform to the conditions of your program and does not necessarily have to be with the symbol < . Everything will depend on the logic of your program.

    answered by 12.02.2018 в 23:24

    The type of cycle for that you present is called for tradicional . According to Wikipedia it was popularized by C programmers.

    Consists of three parts:

    • the initialization : let i = 0;

      Initialization declares (and perhaps assigns) any required variable. The type of a variable must be the same if you are using multiple variables in the initialization part.

      In your case, what you do is initialize i to 0 .

    • the condition :

      It is verified and leaves the loop if the condition is false .

      In your case the condition would be i < length; Here the loop will run as long as i is less than the value of lenght ... the latter can be any value, not necessarily the size of an array.

    • the increase :

      This is done every time the cycle ends and repeats itself.

      In your case, i++ indicates in the code that each time the cycle is repeated, the value of i should increase in 1 .

    The diagram of this for cycle can be represented as follows:

    answered by 12.02.2018 в 23:43

    Your Loop or Cycle for consists of 3 Parts and / or Elements

    1) let i = 0; //Indica el Inicio de Tu Ciclo , It can be a Local Variable declared within the same For as in this case.

    2) i < length; // Una condicional which indicates at what point the For Cycle should be stopped (you can call it if ) while the Condition is fulfilled or not, it will continue to iterate. In your example you are telling him to repeat the Cycle while your variable i is less than length

    3) i++) The way you will increase your Variable i in this case 1 in 1 then your variable will start at 0 and if it meets the condition it is fulfilled or not depending on your logic of If it will continue increasing to 1 validate your if and so on ...

    answered by 12.02.2018 в 23:28