Created
May 11, 2015 19:21
-
-
Save Dilden/de602366cabefbfa88d2 to your computer and use it in GitHub Desktop.
Three functions that compute the sum of the numbers in a given list using a for-loop, a while-loop, and recursion using PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function one($a) { | |
$count = count($a); | |
$total = 0; | |
for ($i=0; $i < $count; $i++) { | |
$total = $total + $a[$i]; | |
} | |
echo $total; | |
} | |
function two($b) { | |
$count = count($b); | |
$start = 0; | |
$total = 0; | |
while ($start < $count) { | |
$total = $total + $b[$start]; | |
$start++; | |
} | |
echo $total; | |
} | |
function three($c) { | |
if(count($c) == 1) { | |
return $c[0]; | |
} | |
else { | |
return array_shift($c) + three($c); | |
} | |
} | |
// $list = 174 | |
$list = array(5, 10, 1, 89, 4, 65 ); | |
one($list); | |
echo "<br>"; | |
two($list); | |
echo "<br>"; | |
echo three($list); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
From here (https://blog.svpino.com/2015/05/07/five-programming-problems-every-software-engineer-should-be-able-to-solve-in-less-than-1-hour)