Hi all,
I hope I describe this correctly... I need to calculate the sum of a range of numbers from user input and give an answer. This is actually an assignment that I need to do and have hit a road block. In short, I have two input fields (form) in html that needs to be verified for numerals, find all the numbers in between, add all the numbers and give an output to the user. Also, the two fields can have the numbers 1 and 10, or 10 and 1, and give the same output. Here's a quick description:
first number: 1
last number: 10
The sum of the numbers in the range is 55 (1+2+3+4+5...)
I apologize, I don't know how to use the tag feature, but here's what I have for code thus far:
<?php // Script - test2.php
// Check if the form has been submitted.
if (isset($_POST['submitted'])) {
if (is_numeric($_POST['a']) && is_numeric($_POST['b'])) {
// Print the heading.
echo '<h1><font color="blue">Sum of Range</font></h1>';
$total = NULL; // Initialize $total.
if ($a <= $b) {
for ($i = $a; $i <= $b; $i++) {
$total = $total + $i;
}
echo '<p><font color="blue">The sum of the range of numbers from ' . $_POST['a'] . ' to ' . $_POST['b'] . ' is ' . $total .'.</font></p>';
} elseif ($a > $b) {
for ($i = $a; $i >= $b; $i--) {
$total = $total + $i;
}
echo '<p><font color="blue">The sum of the range of numbers from ' . $_POST['a'] . ' to ' . $_POST['b'] . ' is ' . $total .'.</font></p>';
}
//echo '<p><font color="blue">The sum of the range of numbers from ' . $_POST['a'] . ' to ' . $_POST['b'] . ' is ' . $total . '.</font></p>';
// Print some spacing.
echo '<p><br /></p>';
} else { // Invalid submitted values.
echo '<h1><font color="red">Error!</font></h1>
<p class="error"><font color="red"><b>Please enter a valid number for a and b.</b></font></p><p><br /></p>';
}
} // End of main isset() IF.
// Leave the PHP section and create the HTML form.
?>
<html>
<body>
<h2>Sum of a Range of Numbers</h2>
<form action="test3.php" method="post">
<p>First Number: <input type="text" name="a" size="5" maxlength="10" value="<?php if (isset($_POST['a'])) echo $_POST['a']; ?>" /></p>
<p>Last Number: <input type="text" name="b" size="5" maxlength="10" value="<?php if (isset($_POST['b'])) echo $_POST['b']; ?>" /></p>
<p><input type="submit" name="submit" value="Calculate!" /></p>
<input type="hidden" name="submitted" value="TRUE" />
</form>
</body>
</html>
If I enter 1 and 10 into my form, I get a response that the $total is equal to 0, and it does post. I'm guessing that I need to keep the $total variable as it runs through the process of increasing or decreasing the value, but I have yet to have any success. I have tried a few global functions, as well as different else-if statements. If I use $_GET['$total'] instead of just $total in the echo statements, it's blank.
I hope this makes sense and appreciate your time and assistance!
Dan