Task Eight - Do Loop - PHP Tutorial
This program repeatedly allows you to enter a number.
It calculates the running total of the numbers you entered.
This program uses a "do" loop. There is more information about "do"
loops here.
Here is a structure diagram of the program.

Here is the result of running the program.

Here is the program code.
<?php
$total = 0;
do
{
echo "Enter a whole number (0 to quit) ... ";
$input = fgets(STDIN);
$total = $total + $input;
echo "\n\nThe running total is $total.\n\n";
}
while ($input <> 0); // While $input is not equal to zero
echo "\n\nFinished.\n\n";
?>
|
Code |
Explanation |
$total = 0; |
Initialise $total to zero. A common program bug is when you forget
to initialise a variable. Many programming languages allow this to happen
and the variable contains garbage data until it is initialised. |
do
{
// Block of code here
}
while (Boolean};
|
This is the structure of the do loop.
The code block between the curly brackets is repeated as long as the
boolean is true. |
Learning Tasks
8 (a) Write a program that calculates the average of the input numbers. It
should
- calculate the running total of the input numbers. (The program above does
this).
- count how many numbers have been input.
- display the count, the running total and the average each time a new number
is input.
- quit if zero is entered.
8 (b) Draw a structure diagram of your program. It will be similar to the one
at the top of this page.
|