Interpretation of repetition loop

6

I'm having trouble understanding the following code that is presented as a book exercise.

$a = true;
$b = -2;
$c = 7;

for ( ; $b < $c || $a; $b++){
    if ($c + $b * 2 > 20)
        $a = false;
        echo $b." ";
}

The result is: -2 -1 0 1 2 3 4 5 6 7

Why is the first parameter of for not passed? I need a full explanation, because I can not assimilate the code with the result.

    
asked by anonymous 10.10.2018 / 00:58

4 answers

6

The narrative would be, b starts execution with -2, and while b is less than c, which in this case is 7, or a is true, the code inside the repeat loop is executed, testing the then the following condition: if b which is -2 * 2 + c that is 7 is greater than 20, it resets the state from a to false, and shows on the screen the value of b concatenated to a empty space. For each loop return, b becomes + 1 by changing its value, the test is redone until the loop condition is satisfied, either by the b < c or a being true. At least one of the two conditions must be true for the loop to happen.

$a = true; // Valor inicial de desta variável.
$b = -2; // Valor inicial de desta variável.
$c = 7; // Valor inicial de desta variável.

// Para cada vez que a repetição contatar que b realmente é menir que c ou a for verdadeiro, executa o código identado após arepetição e acrescenta mais 1 unidade ao valor de b.
for ( ; $b < $c || $a; $b++){
    // Todas as vezes que as condições acima forem satisfeitas, é realizada uma multiplicação, depois uma adição, e por fim, testado se seu valor é mair do que 20.
    if ($c + $b * 2 > 20)
        // Caso as condições acima sejam satisfeitas, o estado de a é modificado para false, e é mostrado na tela o valor de b.
        $a = false;
        echo $b." ";

    // Por fim o loop adiciona uma unidade ao valor de b, conforme citado anteriormente, e o loop volta ao inicio para um novo teste.
}
    
10.10.2018 / 01:38
8

It's a pretty confusing code and I do not know if it's good to try to figure out if you still lack basic knowledge of how syntax works.

for has no parameters, it has 3 statements , or declarations to be made: the initialization of a variable, the condition of stopping it, and the step, usually an increment. If he expects 3 he has to put the 3, even if one of them goes blank, he can not remove the ; because there would be 2.

If you do not need to initialize there any variables do not have to put something, then leave it blank. Rarely does this make sense. If you initialize the variable it will only exist inside the for , but since there is nothing left in this case, you can initialize $b right there.

$c does not change so I see no sense in keeping this variable. Nothing useful is done with $a , so just delete it too.

The whole code has a readability problem, so it gets better and produces the same result:

for ($b = -2; $b < 7; $b++) echo $b . " ";
    
10.10.2018 / 01:33
6
  

After the proper explanation and operation of the FOR loop, both in javascript and PHP (to highlight the similarity of the two), see at the end of this answer, your commented code and running passo a passo in the ideone.

The for statement creates a loop consisting of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement or a sequence of statements executed in sequence.

for ([inicialização]; [condição]; [expressão final])

initialization

An expression (including attribution expressions) or variable declarations. Generally used to start the variable counter. This expression can optionally declare new variables with the keyword var. These variables are non-local in the loop, that is, they are in the same scope as the for loop is. The result of this expression is discarded.

condition

An expression to evaluate before each iteration of the loop. If this expression evaluates to true, statement will be executed. This condition test is optional. If omitted, the condition will always be evaluated as true. If the expression evaluates to false, the execution will go to the first expression after the for loop construct. final expression An expression that will be evaluated at the end of each loop iteration. This occurs before the next assessment of the condition. Usually used to update or increment the counter variable.

statement

A statement that is executed while the condition is true. To execute multiple conditions within the loop, use a block statement ({...}) to group these conditions together. To not execute statements within the loop, use an empty statement (;).

Usage examples

The statement is started by declaring the variable i and initializing it to 0. It checks if i is less than nine, executes the two subsequent statements, and increments 1 to the variable i after each passing through the loop.

for (var i = 0; i < 9; i++) {
   console.log(i);
}

All three expressions in the for loop condition are optional.

For example, in the boot block, it is not necessary to initialize variables:

var i = 0;
for (; i < 9; i++) {
    console.log(i);
}

As with the boot block, the condition is also optional. If you are omitting this expression, you should make sure to break the loop in the body so as not to create an infinite loop.

for (var i = 0;; i++) {
   console.log(i);
   if (i > 3) break;
}

You can also omit all three blocks. Again, be sure to use a break statement at the end of the loop and also modify (increment) a variable, so that the break condition is true at some point.

var i = 0;

for (;;) {
  if (i > 3) break;
  console.log(i);
  i++;
}

SOURCE

With PHP It's pretty similar, see

Usage examples

The statement is started by declaring the variable i and initializing it to 0. It checks if i is less than nine, executes the two subsequent statements, and increments 1 to the variable i after each passing through the loop.

In this first example we have our common FOR, as we all learn:

 <?php

    for($i = 0; $i < 5; $i++)
    {
            echo $i;
            echo '<br />';
    }

In this second example, we remove the first parameter from FOR, and leave the variable $ i set outside the loop:

 <?php

    $i = 0;

    for(; $i < 5; $i++)
    {
            echo $i;
            echo '<br />';
    }

Now, let's take the third parameter, and increment the variable inside the loop.

<?php

    $i = 0;

    for(; $i < 5;)
    {
            echo $i;
            echo '<br />';
            $i++;
    }

Finally, we will remove the second parameter.

<?php

    $i = 0;

    for(; ; )
    {
            echo $i;
            echo '<br />';

            if($i == 5)
            {
                    break;
            }

            $i++;
    }

Want to see it to believe it? São Tomé test on ideone

Notice that in all these examples above, we escape the infinite Loop with some condition or mechanism that we put inside the loop. Be careful. This last example if nothing is done inside the loop, easily generates an infinite loop.

Your commented code

$a = true;
$b = -2;
$c = 7;
$condicao="";


//realiza uma iteração FOR toda vez que $b for menor que $c ou $a for true
//retiramos o primeiro parâmetro do FOR, a variável $b já foi definida fora do laço
for ( ; $b < $c || $a; $b++){

        if ($c + $b * 2 > 20)
        // quando a condição acima for verdadeira, $a se torna false
        $a = false;
        //e a condição FOR já não será mais verdadeira, isto é, zefini, ou seja, "c'est fini"
        echo $b."  ";

}

Follow step-by-step instructions for your code at IDEONE

    
10.10.2018 / 02:03
2

As stated in the comments: " The variable $b is already declared "

The traditional format of the for loop is:

for (
    $i=0; //Declaração de variável
    $i < 10; //Condição para que o loop continue
    $i++ //Ação a cada interação, no caso incremento
) {
}

In your:

//Declaração das variáveis
$a = true;
$b = -2;
$c = 7;

for (
    ; //Não há uma declaração porque ela já foi feita antes
    $b < $c || $a; //Duas condição para continuar o loop, que $b seja menor que $c e $a seja veridadeiro
    $b++ //Incrementa o valor de $b para continuar as iterações
) {
    if ($c + $b * 2 > 20)
        $a = false;
    echo $b." ";
}

It's important to add the first semicolon ( ; ) because, without it, it's like missing a part of the code, PHP does not divide those parts by itself

This code could also be written like this:

for (
    $a = true, $b = -2, $c = 7; //Muda as declarações de lugar
    $b < $c || $a; //Duas condição para continuar o loop, que $b seja menor que $c e $a seja veridadeiro
    $b++ //Incrementa o valor de $b para continuar as iterações
) {
    if ($c + $b * 2 > 20)
        $a = false;
    echo $b." ";
}

Or with another type of loop:

$a = true;
$b = -2;
$c = 7;

while ($b < $c || $a){
    if ($c + $b * 2 > 20)
        $a = false;
    echo $b++." ";
    //O incremento poderia ser numa linha separada mas para reduzir deixei assim
}

Note:

  • Line breaks within for is just to increase readability
  • Caution, your echo has tab more, giving the impression that it will only run if the if condition is true, which is not the case. Without the keys ( { } ) only the next command of if will be "inside it"
10.10.2018 / 01:54