0

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.

1
  • This won't fulfil your homework assignment, but array_sum(range(1,10)) would do. Commented Mar 23, 2011 at 4:28

4 Answers 4

3

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;
Sign up to request clarification or add additional context in comments.

14 Comments

agreed, some people are to helpful
that's not an example its an answer.
@Prisoner: Figuring out an answer for yourself proves much more fruitful and rewarding.
It looks like you just re-wrote the question with pseudo-code. How is this an answer to the question about php and loops?
@Russel, I do agree but when you have no idea where to start seeing some examples and links to relevant information is much more helpful than sitting there hacking it to work over the space of an hour (in my opinion).
|
0
<?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

1 Comment

others also works but this one is well commented so i'll choose this as answer.
0

I would use a for loop.

$total = 0;

for($i = 1; $i <= 10; $i++){
  $total += $i;
}

Comments

0

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.