Enter a number and display the next 100 even numbers

Asked

Viewed 1,067 times

2

I’m making a program that receives any number and displays the next 100 even numbers, but as soon as I open the site it’s already displaying a result without even typing anything.

<!doctype html>
<html lang="pt-bt">

<head>
    <title>Exercicio 3</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link href="css/exercicio3.css" rel="stylesheet" type="text/css">


    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
</head>

<body>

    <!--Barra de Navegação-->
    <nav class="navbar navbar-expand-lg  navbar-dark bg-primary">
        <a class="navbar-brand" href="#">Exercicios de PHP</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarText" aria-controls="navbarText" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarText">
            <ul class="navbar-nav mr-auto">
                <li class="nav-item">
                    <a class="nav-link" href="index.html">Exercicio 1</a>
                </li>
                <li class="nav-item ">
                    <a class="nav-link" href="exercicio2.php">Exercicio 2</a></a>
                </li>
                <li class="nav-item active">
                    <a class="nav-link" href="#">Exercicio 3</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">Exercicio 4</a>
                </li>
            </ul>
        </div>
    </nav>

    <div class="container">

        <h3 class="page_header">Exercicio 3</h3>


        <div class="row">
            <div class="col-sm-6 ">
                <div class="area_conteudo">
                    <h4 class="title_form">Faça o calculo a baixo</h4><br>

                    <form class="posicao" name="formulario" method="GET" action="exercicio3.php">
                        <label>Digite um valor inteiro</label>
                        <div class="form-group">
                            <input type="number" id="tamanho" class="form-control " name="numero" placeholder="Digite um numero">
                        </div>
                        <input type="submit" class="btn btn-primary" value=" Calcular">
                    </form>

                    <h3 class="texto_resultado">Resultado:</h3>


                    <!--PHP-->

                    <?php 
                    $numero = $_GET['numero'];
                    $c = 0;
                    while ($c <= 100) {
                      if ($numero % 2 == 0) {
                        echo "$numero ";
                      }
                      $numero++;
                      $c++;
                    }

                    ?>

                    <!--FIM-PHP-->
                </div>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
</body>

</html> 
  • The number is probably in the URL. Because the method you use is $_GET.

  • Your url should look like this: exercicio3.php?numero=12 right?

3 answers

4

The $_GET is a global variable Seper that contains the values of query string of the URL

Query String are all characters after interjection ("?")

What probably happens is that you are passing this value directly through the URL and not through the form

A simple way to avoid this is to use the verb HTTP POST instead of GET:

<!-- ... -->
<form class="posicao" name="formulario" method="POST" action="exercicio3.php">
    <label>Digite um valor inteiro</label>
    <div class="form-group">
        <input type="number" id="tamanho" class="form-control " name="numero" placeholder="Digite um numero">
    </div>
    <input type="submit" class="btn btn-primary" value=" Calcular">
</form>

<h3 class="texto_resultado">Resultado:</h3>

<!--PHP-->

<?php 
$numero = $_POST['numero'];
$c = 0;
while ($c <= 100) {
  if ($numero % 2 == 0) {
    echo "$numero ";
  }
  $numero++;
  $c++;
}
// ...

Thus the variable numero will be sent by the body of the request and no longer by the URL

2

To william’s response already explains the probable cause of your program to display the result without you typing anything. I would just like to suggest an improvement in your algorithm.

If you want to iterate through even numbers, you don’t need to add one to one and test if it’s even. Just start with an even number and go adding 2 to 2:

$numero = // obter o valor do número

// pega o próximo número par (mas se já for par, não incrementa)
$numero += ($numero % 2);

for ($i = 0 ; $i < 100; $i++) {
  echo "$numero ";
  $numero += 2; // pega o próximo número par
}

Over the line $numero += ($numero % 2):

  • if the number is even (if $numero % 2 is zero), will be summed zero (ie the number is already even, I can start by itself)
  • if the number is odd (if $numero % 2 is not zero - and therefore will be 1), I add 1 (so that the number starts with the next even value)

So I guarantee that the for will always start from an even number. Of course you can also exchange this line for:

// se for ímpar, ajusta para o próximo número par
if ($numero % 2 != 0) {
    $numero++;
}

Choose what you think is best.


Within the for i print the number and sum 2 to get the next even number (and do it 100 times).

If you want, you can even increase the number along with the $i:

for ($i = 0 ; $i < 100; $i++, $numero += 2) {
  echo "$numero ";
}

Another point is that your code is not doing what it should:

$c = 0;
while ($c <= 100) {
  if ($numero % 2 == 0) {
    echo "$numero ";
  }
  $numero++;
  $c++;
}

If the number is even, print. But it always increases $c, even if the number is not even. The result is that only 50 even numbers will be printed (or 51 if it starts at an even number, because of the <=).

To correct, just think what the $c means: it is counting the amount of even numbers that have been printed. So you can only increment $c if the number is even. And I must stop if the value of it reaches 100 (therefore the while must use < instead of <=):

$c = 0;
while ($c < 100) {
  if ($numero % 2 == 0) {
    echo "$numero ";
    $c++; // só incrementa $c se o número for par
  }
  $numero++;
}

This will print 100 even numbers correctly. But I still prefer the option I suggested above, because there is no need to iterate 1 in 1 and make a if at each iteration.

1

To display 100 next even numbers, I would do something like this:

$numero = $_GET['numero'];
                $inicio = 0;
                $fim = 100;
                while ($inicio<= $fim) {
                  if ($numero % 2 == 0) {
                    echo "$numero ";
                    $inicio++
                  }
                  $numero++;
                }
                ?>

This way he will make the 100 loops, and will check which number is the pair. another option, which would decrease the process time of php would be like this:

$numero = $_GET['numero'];
                $fim = $numero + 200;
                while ($numero<= $fim) {
                  if ($numero % 2 == 0)
                      {
                                echo "<br>".$numero;
                      }    
                  elseif ($numero % 2 != 0)
                      {
                                $numero++;
                                echo "<br>".$numero;
                      }    

                $numero= $numero +2;
                }
                ?>

In this scheme, it will jump to the even number. If it starts from an odd number, it will consider, add one, and then proceed with the same process.

  • With the tips I managed to tidy up, thank you very much.

  • You are welcome, if you can mark one of the answers as correct, so that someone else with the same problem will find the same help that you have sought more easily

Browser other questions tagged

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