Reputation: 3
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.
Upvotes: 0
Views: 1007
Reputation: 73392
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;
Upvotes: 3
Reputation: 64177
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));
Upvotes: 0
Reputation: 22278
I would use a for
loop.
$total = 0;
for($i = 1; $i <= 10; $i++){
$total += $i;
}
Upvotes: 0
Reputation: 27638
<?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
Upvotes: 0