1

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!

5 Answers 5

4
<?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

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

Comments

2

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

1 Comment

sorry.. I removed my answer, I did not see that you pointed out this before.. +1 for showing the smart solution :)
0
<?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.

Comments

0

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.

Comments

0

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>

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.