0

Hello: I'm new programming. My problem is that the evaluation in the for sentence is not working properly.

With: salir='n' it works correctly
With: salir=='n' don't works.

Thanks

<script type="text/javascript">
    var tabla="";
    var numusuario=0;
    var min=0;
    var max=9;
    var salir='s';
    numusuario=prompt("Escribe un número entre 0 y 9: ");
    for(var j=1;salir='n';j++) 
    {
        if(numusuario<0 || numusuario>=10)
        {
            salir='s';
            numusuario=prompt("Escribe un número entre 0 y 9: ");
        }
        else
        {
            for(var x=min;x<=max;x++)
            {
                tabla = tabla + x + " x " + numusuario + " = " + (x*numusuario) + "\n";
            }
            alert(tabla);
            break;
        }
    }
</script>
1
  • you should make deeper research with for loop Commented Mar 6, 2020 at 11:10

2 Answers 2

2

salir='n' means assignments. it is always return true

salir=='n' means comparision. it is return false because salir='s' so s is not equal to n

Sign up to request clarification or add additional context in comments.

Comments

0

Several things happenning here, but main is that you are mixing different forms of flow control:

  • You are using salir (exit, for non-spanish speakers) as a loop end indicator, but...
  • The loop condition is always true (as salir='n' evaluates to 'n', which is true)
  • You are using also a variable, j, with no use (you do nothing with it, it doesn't participate in the loop condition neither)
  • The only posibility of exiting the loop is the break sentence, which exists the loop.

As the expected behaviour is not clear to me, I cannot assume a solution, but if it is to keep running until the user writes a valid number, then write the multiplication table of that number, it could be:

<script type="text/javascript">
    var tabla="";
    var numusuario=0;
    var min=0;
    var max=9;
    var salir = 'n';

    do {
        numusuario=prompt("Escribe un número entre 0 y 9: ");
        if(numusuario>0 && numusuario<10) {
            for(var x=min;x<=max;x++)
            {
                tabla = tabla + x + " x " + numusuario + " = " + (x*numusuario) + "\n";
            }
            alert(tabla);
            salir = 's';
        }
    } while(salir == 'n')


</script>

The do {} while () executes at least once and checks the condition at the end, that seems better suited in this case, we drop the j variable and use the salir variable as flow control until the user writes the correct number.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.