[PHP] Add all previous numbers in a for loop
#1

I have this simple for loop:

Код:
for($i = 1; $i <= 7; $i++) {

    echo $i . "<br>";

}
Which outputs:

Код:
1
2
3
4
5
6
7
Now what I want is to add all the previous numbers on each loop. So the output should be:

Код:
1
2 // current number + all above
3 // current number + all above
6 // current number + all above
12 // current number + all above
24 // current number + all above
48 // current number + all above
I tried this:

Код:
$sum = 0;

for($i = 1; $i <= 7; $i++) {

    $sum = $sum + $i;

    echo $sum . "<br>";

}
But this is the output I get:

Код:
1
3
6
10
15
21
28
How can I get the desired results?
Reply
#2

Dont get me wrong but this forum is all about pawn and sa-mp.
Reply
#3

Quote:
Originally Posted by Banditul18
Посмотреть сообщение
Dont get me wrong but this forum is all about pawn and sa-mp.
I mean you can take this as a pawn question since both pawn and php are quite similar.
Reply
#4

The output you get is correct, it does the thing you described... Your "desired" output is the value of $i until 3 and from then on it's 3 ^ ($i - 2).
Reply
#5

Until three, you can make them static, after that simple current number * 2;
Код:
            Console.WriteLine(1);
            Console.WriteLine(2);
            Console.WriteLine(3);
            var res = 3;
            for (int i = 0; i < 7; i++)
            {
                res *= 2;
                Console.WriteLine(res);
            }
Reply
#6

Quote:
Originally Posted by benjaminjones
Посмотреть сообщение
Until three, you can make them static, after that simple current number * 2;
Код:
            Console.WriteLine(1);
            Console.WriteLine(2);
            Console.WriteLine(3);
            var res = 3;
            for (int i = 0; i < 7; i++)
            {
                res *= 2;
                Console.WriteLine(res);
            }
It's actually not multiplied by 2, it's add all previous numbers on each loop.
Reply
#7

Quote:
Originally Posted by Mr.Anonymous
Посмотреть сообщение
It's actually not multiplied by 2, it's add all previous numbers on each loop.
If you add all the previous numbers on each loop, the result you get is the same as the result you get, if you start from 3 and multiply from there. The code I provided produces the same result, as the one you've described.
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)