Interpretation of loop of repetition

Asked

Viewed 324 times

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

Because the first parameter of for is not past ? I need a complete explanation because I cannot assimilate the code with the result.

  • The variable $b is already stated, so it would be the same as for($b = -2; $b < $c || $a; $b++)

  • Do you have other parts of this code or is this all? Change everything if you have other parts.

  • is just that. But because the dot is comma at the beginning of the is ? if the delete returns an error

  • But the problem wasn’t the first statement of for? You switched acceptance to an answer that doesn’t even touch the subject?

4 answers

10

It’s a very confusing code and I don’t know if it’s good to try to understand if you still lack basic knowledge of how syntax works.

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

If you do not need to initialize some variable there is no reason to put something, then you leave it blank. Rarely does this make sense. If initialize the variable will only exist inside the for, but as in this case has nothing else can initialize $b right there.

$c does not vary so I see no sense to keep this variable. Nothing useful is done with $a, then just take her out 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 . " ";

I put in the Github for future reference.

  • Aah gave to assimilate the situation now. Really does not make much sense this code. But the intention of the book is to leave the more articulate reasoning to the programming, so most of the exercises are somewhat exaggerated. But I got it right now. Vlw by force. Hug

  • 1

    So I consider this a bad source, creates addictions, misrepresents the thought, should look for something that makes sense.

  • I always comment when I vote no. The AP did not ask for improvements or a better way to accomplish the task, he just wanted to understand the logic of the exercise that was given, thing you did not do in your reply.

  • 1

    @Leocaracciolo I answered what was in the question that is what makes the first "parameter* blank, and showed that it did not need to be blank. And you don’t forget that I’m a moderator and I know you don’t comment on everything negative, but it’s okay not to do it. Is there something wrong with the answer? Have I taught you wrong? Have I not answered what was strictly asked? It is your right to use whatever criteria you want, but the answer is not wrong to receive a negative. It teaches something useful, and better, hereafter to have answered what was asked. Using your criterion I must deny yours by putting JS

  • Eu preciso de uma explicação completa, pois não consigo assimilar o código com o resultado.

  • 1

    Let’s ignore the fact that the author of the question said, "Aah has assimilated the situation now." in the first comment, which is to justify this conversation is taking place :D

  • Um, I threw a green one and I picked it ripe, which means moderator knows who’s negative. I heard from a grad student once that even moderator doesn’t know who’s negative. The episode occurred because someone was thinking he was being chased by some guy who was constantly voting against his answers.

  • @Leocaracciolo is not like that, you can know "who is negative and does not comment" as he said, because there are general statistics. Only CM can see individual voting (this has already been well debated in the official chat, can give a search there). A lot of this even people who do not have special powers know. Just see the number of negatives in the person’s profile, and how much she comments.

  • 1

    For example, had user improperly using network comments as spam for moderator campaign (which shows what kind of people we are dealing with), probably this person does not know that we all see the history, but it exists. Often the lack of knowledge of the tool leads to hasty conclusions, or to finding that certain people have more privileges than others.

Show 4 more comments

7


The narrative would be, b begins execution with -2, and while b is less than c, which in this case is worth 7, or a is true (true), the code from within the repeat loop runs, testing the following condition: if b that is worth -2 * 2 + c that is worth 7 is greater than 20, resets the state from a to false (false), and shows on the screen the value of b concatenated to an empty space. For each loop in the loop, b starts to assert itself + 1 by changing its value, the test is redone until the condition of the loop is not satisfied, either by the test of 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.
}
  • Your answer is right, only that part... "The two conditions must be true for the loop to happen."... Actually no. Actually ONE of the conditions need to be & #Xa; true for the loop to happen.

  • So this part would have to stay like this ".. the test is redone until (none) (d)a(s) condition(s) of the loop is not (m) satisfied(s) BOTH by the test of b < c E a being true..."

  • || is E or OU?

  • Yes, I had hesitated, but I already made the correction in the answer.

5

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

The for statement creates a loop consisting of three optional expressions, within 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 assignment expressions) or variable statements. Usually used to start the variable counter. This expression can optionally declare new variables with the var keyword. These variables are not local in the loop, i.e., they are in the same scope as the for loop is. The result of this expression is discarded.

condition

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

statement

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

Examples of use

The declaration starts by declaring the variable i and initializing it as 0. It checks if i is less than nine, executes the two subsequent instructions and increments 1 variable i after each passage 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, make sure to use a break instruction at the end of the loop and also modify (increment) a variable, so 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 very similar, see

Examples of use

The declaration starts by declaring the variable i and initializing it as 0. It checks if i is less than nine, executes the two subsequent instructions and increments 1 variable i after each passage 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 take the first parameter from FOR, and leave the $i variable defined 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 within 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 to believe? São Tomé test on ideone

Note that in all of 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 the step by step of your code on IDEONE

  • In his case the language is PHP good part applies and parts do not.

  • @Noobsaibot, kkk, hadn’t even noticed the tag

3

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

The traditional format of the loop for 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 his:

//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 is important to add the first semicolon (;) because without it, it’s like missing a piece of code, PHP doesn’t divide those parts on its own

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 kind 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
}

Observing:

  • The line breaks within the for is only to increase readability
  • Watch your step, man echo has a tab further, giving the impression that it will only be executed if the condition if be true, which is not the case. Without the keys ({ }) only the next command of if will be "inside of it"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.