Pro-grammer
Pro-grammer

Reputation: 870

calculating values from input, in PHP

I'm studying for finals and i came across this question:

Write a php script to read a positive integer, n from a input box and calculate the value of 1+2+-- n...

ive have tried for long and done sufficient research, but i have not been able to complete this so far i have:

<html>
  <head>
    <title>
     </title>
 </head>
 <body>
  <form action="inputnum.php" method="post" >
   num:<input type="text" name="num" size ="5"/>
  <input type = "submit" value = "Submit Order" />

       <?php
        $num=$_POST["num"];
        if ($num==0)$num=="";
         for($i=0; $i<=$num; $i++){
         }
            echo"($num+$i)";
       ?>

  </form>

can anyone help me out? Thanks in advance!

Upvotes: 1

Views: 9718

Answers (5)

sorcix
sorcix

Reputation: 64

You could use something like this (not tested, no PHP interpreter available here):

<html>
    <head>
        <title></title>
    </head>
    <body>

        <?php

            $num = (int)$_POST['num'];

            if(!$num) {

        ?>

        <form action="inputnum.php" method="post" >

            num: <input type="text" name="num" size ="5"/>
            <input type = "submit" value = "Submit Order" />

        </form>

        <?php

            } else {

                $total = 0;
                for($i=1; $i<=$num; $i++){

                    $total = $total + $i;

                }
                echo $num;

            }

        ?>

    </body>
</html>

Upvotes: 0

Anri&#235;tte Myburgh
Anri&#235;tte Myburgh

Reputation: 13517

Firstly, this if ($num==0)$num==""; is wrong. $num=""; is what it should be. And in anycase, this would break your if-statement.

I would suggest putting the for-loop in the if-statement and changing the condition to $num>0.

Let $i begin from 1, not 0.

Upvotes: 0

matino
matino

Reputation: 17715

You mixed up paranthesis, you also mix = with ==. Anyway there exists a faster way of computing such sum, i.e. n * (n + 1) / 2

Upvotes: 2

heyanshukla
heyanshukla

Reputation: 669

<?php
    $num=$_POST["num"];
    if ($num==0)$num="";
    else
    {
     for($i=0; $i<=$num; $i++){
       $sum=$sum+$i;
       }
    }
    echo $sum;
   ?>

To be more precise you must first check whether the submit button is set or not before calculating the sum.

Upvotes: 0

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123377

<?php
  $num   = (int)$_POST["num"];
  $total = 0;

  for ($i=0; $i <= $num; $i++) {
     $total = $total + $i;
  }

  echo $total;
?>

If your code is expecting to deal with a number, it's better to do an explicit casting via (int) of the posted value

Upvotes: 3

Related Questions