PHP: Here is what I am supposed to accomplish. And below is my code. I am definitely missing something..
Write a FOR loop using an array that prints “The product of first 10 numbers is ” followed by the product of numbers 1 through 10. Here’s a hint: do NOT begin counter at 0 or else the product will be a zero!
<?php
$numbers = 0;
$numbers = range(1 , 10);
$arrlength = count($numbers);
for ($x = 1; $x <= $arrlength; $x++) {
$numbers[$x] = $numbers + $x;
}
echo "The product of first 10 numbers is $numbers.<br>";
?>
Essentially what you're doing is creating a factorial function for a limited case. The problems with your implementation are that you seemed to re-use the $numbers variable when it should be one variable to hold the product and one for the array 1-10. The second issue is in your loop where you loop from 1-10 but what you probably really want to do is loop from 0-9 which are the array indices so that you can get the values from the array like this:
<?php
$prod = 1;
$numbers = range(1 , 10);
$arrlength = count($numbers);
for ($x = 0; $x < $arrlength; $x++) {
$prod *= $numbers[$x];
}
echo "The product of first 10 numbers is $prod.<br>";
?>
The output of which will be:
The product of first 10 numbers is 3628800.
Please note I have not tested this code, but I'm sure it should work.
<?php
$numbers = range(1, 10);
$product = 1;
for ($i = 0; $i < count($numbers); $i++) {
$product *= $numbers[$i];
}
echo 'The product of the first 10 numbers is ' . $product . '<br />';
?>
Related
Recently, my exams got over. My last exam was based on PHP. I got the following question for my exam:
"Convert the following script using for loop without affecting the output:-"
<?php
//Convert into for loop
$x = 0;
$count = 10;
do
{
echo ($count. "<BR>");
$count = $count - 2;
$x = $x + $count;
}
while($count < 1)
echo ($x);
?>
Please help me as my computer sir is out of station and I am really puzzled by it.
Well, If I understand well, You have to use "for" loop, instead of "do...while", but the printed text must not change.
Try:
$count = 10;
$x = 0;
$firstRun = true;
for(; $count > 1 || $firstRun;) {
$firstRun = false;
echo ($count . "<BR>");
$count -= 2;
$x = $x + $count;
}
echo ($x);
By the way loop is unnecessary, because $count will be greater than 1 after the first loop, so the while will get false.
EDIT
$firstRun to avoid infiniteLoop
$count in loop
EDIT
Fixed code for new requirement
Removed unnecessary code
Hmmm I don't know if your teacher wanted to own you... but the do{} will execute only once since $count is never < 1.
The output of your teacher's code is:
10
8
I presume there was a mistake in the code and the while would be while($count > 1) which would make more sense (since it's weird to ask for a loop to output only 10 8) and would result in this output:
10
8
6
4
2
20
Then a good for() loop would have been :
$x = 0;
$count = 10;
for($i = $count; $i > 1; $i -= 2)
{
$count -= 2;
echo $i . "<br>";
$x += $count;
}
echo $x;
Which will output the same values.
If you can, ask your teacher for this, and comment the answer ^^ ahahah
I'm trying to use ONE PHP for loop to echo the sum of the numbers 1-10 as well as echo the sum of only the even numbers. I seem to have a problem as these iterations won't be "parallel"
Code:
<?php
$sum = 0; $evensum = 0;
for($x = 1, $y=2; $x<=10, $y<=6; $x++, $y += 2) {
$sum = $sum + $x; $evensum = $evensum + $y;
}
echo "total sum= ". $sum, ", even sum=" . $evensum;
?>
total sum should reflect 55 (1+2+3+4+5+6+7+8+9+10) and even sum should reflect 30 (2+4+6+8+10)
Just Use
<?php
$sum = 0; $evensum = 0;
for($x = 1; $x<=10; $x++) {
// sum all the number
$sum = $sum + $x;
// check the number is even
if( $x % 2 === 0 ) {
// sum only the even numbers
$evensum = $evensum + $x;
}
}
// output
echo "total sum= ". $sum, ", even sum=" . $evensum;
?>
Another approach is using range() and array_functions
$arr=range(1,10);
echo $sum=array_sum($arr);
function even($var)
{
return(!($var & 1));
}
echo $even=array_sum(array_filter($arr, "even"));
Sum all ranges
$all_sum=array_sum(range(1,10));
Sum even number (0,2,4,6,8,10)
$even_sum = array_sum(range(0,10,2));
I need to find the averege after using a loop counting ever 3rd to a 100. The loop part is easy enough, but I need to sum every value then divide the sum on the total of values.
for ($x = 3; $x < 100; $x+=3) {
echo $x.", ";
}
This is the loop I need to use. How to I sum the values this produces and how do I find how many values this loop produces?
I believe the intention here is to learn about loops, otherwise this stuff can be done without looping too.
For learning purpose, you can simply introduce two variables count and sum and compute them inside the loop. For count, you just increment it on each iteration. For sum, you add the current value of x into sum. After the loop you print both variables.
$count = 0;
$sum = 0;
for ($x = 3; $x < 100; $x+=3) {
echo $x.", ";
$count++;
$sum+=$x;
}
echo $sum;
echo $count;
add your elements into an array and then use array_sum to sum the array elements , then divide the sum by the count of your array
$arr = [];
for ($x = 3; $x < 100; $x+=3) {
// echo $x.", \n";
$arr[] = $x;
}
print_r(array_sum($arr) / count($arr));
// Output : 51
$i=0;
$tempx=0;
for ($x = 3; $x < 100; $x+=3) {
//total sum
$tempx = $tempx + $x;
//count of how many times the loop ran in this case 33 times
$i++;
}
//first $i was 0 so we add 1
$i=$i + 1;
//getting the average
$average=$tempx / $i;
echo $average;
//output
For the last answer i think we should not do:
//first $i was 0 so we add 1 $i=$i + 1;
Regards
hello i'm beginner for programming I've got a homework. googled it but couldnt find anything...
i need to get the total value of numbers from 1 to 10. this need to be done in loop. but couldn't figure which loop should i use. if you can also give me an example code thats would be great.
This is a homework question, I'm not sure why people are just giving you an answer to copy-paste.
Achieving the sum of numbers 1..10 is pretty simple. You will need to initialise an empty int var before your loop, and for each iteration from 0 up to and including 10 you will add your int var to the current iteration.
For example:
sum = 0;
for num in range 1 to 10:
sum = sum + num;
<?php
$start = 0; // set the variable that will hold our total
for($i=1;$i<11;$i++){ // set a loop, read here: http://php.net/manual/en/control-structures.for.php for more info
$start += $i; // add $i to our start value
}
echo $start; // display our final value
I would use a for loop.
$total = 0;
for($i = 1; $i <= 10; $i++){
$total += $i;
}
Using the for loop:
<?php
$sum = 0;
for($i = 1; $i <= 10; $i++){
$sum += $i;
}
Using the foreach loop:
<?php
$sum = 0;
foreach(range(1,10) as $num){
$sum += $num;
}
echo $sum; // prints 55
And disregarding your assignment, here is an easier way:
echo array_sum(range(1,10));
How do I find the sum of all the digits in a number in PHP?
array_sum(str_split($number));
This assumes the number is positive (or, more accurately, that the conversion of $number into a string generates only digits).
Artefactos method is obviously unbeatable, but here an version how one could do it "manually":
$number = 1234567890;
$sum = 0;
do {
$sum += $number % 10;
}
while ($number = (int) ($number / 10));
This is actually faster than Artefactos method (at least for 1234567890), because it saves two function calls.
Another way, not so fast, not single line simple
<?php
$n = 123;
$nstr = $n . "";
$sum = 0;
for ($i = 0; $i < strlen($nstr); ++$i)
{
$sum += $nstr[$i];
}
echo $sum;
?>
It also assumes the number is positive.
function addDigits($num) {
if ($num % 9 == 0 && $num > 0) {
return 9;
} else {
return $num % 9;
}
}
only O(n)
at LeetCode submit result:
Runtime: 4 ms, faster than 92.86% of PHP online submissions for Add Digits.
Memory Usage: 14.3 MB, less than 100.00% of PHP online submissions for Add Digits.
<?php
// PHP program to calculate the sum of digits
function sum($num) {
$sum = 0;
for ($i = 0; $i < strlen($num); $i++){
$sum += $num[$i];
}
return $sum;
}
// Driver Code
$num = "925";
echo sum($num);
?>
Result will be 9+2+5 = 16
Try the following code:
<?php
$num = 525;
$sum = 0;
while ($num > 0)
{
$sum= $sum + ($num % 10);
$num= $num / 10;
}
echo "Summation=" . $sum;
?>
If interested with regex:
array_sum(preg_split("//", $number));
<?php
echo"----Sum of digit using php----";
echo"<br/ >";
$num=98765;
$sum=0;
$rem=0;
for($i=0;$i<=$num;$i++)
{
$rem=$num%10;
$sum=$sum+$rem;
$num=$num/10;
}
echo "The sum of digit 98765 is ".$sum;
?>
-----------------Output-------------
----Sum of digit using php----
The sum of digit 98765 is 35
// math before code
// base of digit sums is 9
// the product of all numbers multiplied by 9 equals 9 as digit sum
$nr = 58821.5712; // any number
// Initiallization
$d = array();
$d = explode(".",$nr); // cut decimal digits
$fl = strlen($d[1]); // count decimal digits
$pow = pow(10 ,$fl); // power up for integer
$nr = $nr * $pow; // make float become integer
// The Code
$ds = $nr % 9; // modulo of 9
if($ds == 0) $ds=9; // cancel out zeros
echo $ds;
Assume you want to find the sum of the digits of a number say 2395 the simplest solution would be to first split the digits and find out the sum then concatenate all the numbers into one single number.
<?php
$number=2;
$number1=3;
$number2=9;
$number3=5;
$combine=$number.$number1.$number2.$number3;
$sum=$number+$number1+$number2+$number3;
echo "The sum of $combine is $sum";
?>
One way of getting sum of digit however this is a slowest route.
$n=123;
while(($n=$n-9)>9);
echo "n: $n";
<html>
<head>
<title>detail</title>
</head>
<body>
<?php
$n = 123;
$sum=0; $n1=0;
for ($i =0; $i<=strlen($n);$i++)
{
$n1=$n%10;
$sum += $n1;
$n=$n/10;
}
echo $sum;
?>
</body>
</html>
Here's the code.. Please try this
<?php
$d=0;
$num=12345;
$temp=$num;
$sum=0;
while($temp>1)
{
$temp=$temp/10;
$d++;
}
echo "Digits Are : $d </br>";
for (;$num>1;)
{
$d=$num%10;
$num=$num/10;
$sum=$sum+$d;
}
echo "Sum of Digits is : $sum";
?>