0
Can some one tell me how following code execute ' which lines is executing ist and how can some one show me that mathematically
<?php for($i = 1 ; $i <= 5 ; $i++) { for($y = 1; $y <= $i; $y++) { echo $i; } echo "<br />"; } output : 1 22 333 4444 55555
6 Respostas
+ 4
The first (outer) loop is the "row" counter (Y axis) it will repeat the instructions for five times.
for($i = 1 ; $i <= 5 ; $i++) {
The second (inner) loop is the "column" counter (X axis). It will repeat as many times as the value of $i, the iterator of the outer loop.
for($y = 1; $y <= $i; $y++) {
echo $i;
}
$i $y (range) action for inner loop
1 1-1 print "1" once
2 1-2 print "2" twice
3 1-3 print "3" thrice
4 1-4 print "4" four times
5 1-5 print "5" five times
// prints line break so the next iteration will print
// the output on the next line
echo "<br />";
}
output :
1
22
333
4444
55555
Hth, cmiiw
+ 4
Iteration is the process a loop "walks through" from the initial value to the final value. If you make a for...loop to repeat five times, the for loop is said to have five iterations to complete before it reaches the final value (5).
An iterator is a variable that changes its value throughout the process of loop works, in your code $i and $y are iterators. When a loop is said to iterate, it changes the iterator value so it "remembers", how many times it had iterated, and to check, whether if the iterator has reached the specified final value, where the loop eventually stops repeating.
Every time the inner loop iterates (repeats) it prints the value of the outer loop's iterator ($i) as many times as the $i value. So ...
When $i value = 1
Inner loop repeats 1 time (because $i = 1) and prints the value of $i (which is 1), one time, hence "1"
When $i value = 2
Inner loop repeats 2 times (because $i = 2) and prints the value of $i (which is 2), two times, hence "22"
When $i value = 3
Inner loop repeats 3 times (because $i = 3) and prints the value of $i (which is 3), three times, hence "333"
And so on, until... $i value = 5
Inner loop repeats 5 times (because $i = 5) and prints the value of $i (which is 5), five times, hence "55555"
Hth, cmiiw
+ 3
Look at the top of the list, there I put $i $y (range) ...
To read the
When the outer loop $i value = 1
Inner loop $y iterates once (1)
When the outer loop $i value = 2
Inner loop $y iterates twice (1 and 2)
When the outer loop $i value = 3
Inner loop $y iterates three times (1, 2 and 3)
And so on, until outer loop $i value = 5...
Inner loop iterates five times (1,2,3,4 and 5)
On each inner loop iteration, a value of $i is printed. Hope you can understand this better.
Hth, cmiiw
+ 2
thank u ipang gotted u
0
2 1-2 print " 2" twice .... i did not understand how this happens ?? where the " 1" comez from ie 1-2
0
here the word iterates means suggestion .
if outer loop is 3 ' then inner loop will suggest to print 3 three timez ie is 123 times ..
outerloop=4
innerloop suggest to print it four times
ie1234 times ??
am i right ??