John Davidson

How to add 3 numbers by loop using these 3 loops [ for, do , do while loop] in php

0 comments
Message:


I'm starting to learn php today and I cannot figure out how to sum all 3 numbers by these loops [for, do, do while] loop. I can't even get passed through for loop.


Here is my current code :


<?php

$sum =0;

@$a= $_GET['a'];
@$b= $_GET['b'];
@$c= $_GET['c'];

for($i = $a; $i<=$c; $i++)
{
$sum = $a++;
}

echo "Sum of $a , $b , $c is ".$sum;

?>

<body>

<form>

Enter first number <input type = "text" name="a"><br>

Enter second number <input type = "text" name="b"><br>

Enter third number <input type = "text" name="c"><br>

<input type = "submit" value="add">

</form>

</body>


My Answer:
Here is the corrected code using the for loop to sum all 3 numbers:

php

$sum = 0;

$a = $_GET['a'];
$b = $_GET['b'];
$c = $_GET['c'];

for ($i = $a; $i <= $c; $i++) {
$sum += $i;
}

echo "Sum of $a , $b , $c is " . $sum;

?>


You can also achieve the same result using the do-while loop or while loop. Here is an example using the do-while loop:

php

$sum = 0;

$a = $_GET['a'];
$b = $_GET['b'];
$c = $_GET['c'];

$i = $a;
do {
$sum += $i;
$i++;
} while ($i <= $c);

echo "Sum of $a , $b , $c is " . $sum;

?>


And here is an example using the while loop:

php

$sum = 0;

$a = $_GET['a'];
$b = $_GET['b'];
$c = $_GET['c'];

$i = $a;
while ($i <= $c) {
$sum += $i;
$i++;
}

echo "Sum of $a , $b , $c is " . $sum;

?>


You can choose any of these loop structures to sum all 3 numbers in PHP.

Rate this post

3 of 5 based on 1235 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us