Reputation: 11
I tried to do a while
inside a while
to print a multiplication table like,
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
But I got only 1, 2, 3, 4, 5.
$i = 1;
$x = 1;
while($i <= 5){
while($x <= 5){
echo $i * $x;
$x++;
}
echo "<br>";
$i++;
}
Upvotes: 1
Views: 8861
Reputation: 6215
You need to reset $x
, so:
$i = 1;
$x = 1;
while($i <= 5){
while($x <= 5){
echo $i * $x;
$x++;
}
$x = 1; // added this line
echo "<br>";
$i++;
}
Output:
12345
246810
3691215
48121620
510152025
You can then do what ever you want to format it.
More elabrate explanation:
It enters both outer and inner loops, showing the desired output for the first line. You end up with $i = 2
and $x = 6
.
Since $i
is 2
, it doesn't leave the outer loop, but $x
is 6
, so it doesn't enter the inner loop again.
It then keeps adding 1
to $i
until it doesn't match the outer loop condition anymore and leaves you with that unwanted result.
Upvotes: 2
Reputation: 603
This is happening because you're not resetting $x
when the inner loop completes its iteration. Try this instead:
$i = 1;
while($i <= 5) {
$x = 1;
while($x <= 5) {
echo $i * $x;
$x++;
}
echo "<br>";
$i++;
}
Upvotes: 3
Reputation: 7294
Use this
This is because you have not initialized
your $x
after external while loop
completes its one cycle
. so after one cycle inner loops
does not run
<?php
$i = 1;
while($i <= 5) {
$x = 1;
while($x <= 5) {
echo $i * $x;
$x++;
}
echo "<br>";
$i++;
}
Upvotes: 1
Reputation: 1945
php code:
$i = 1;
while($i <= 5){
$x = 1;
while($x <= 5){
echo $i * $x." ";
$x++;
}
echo "<br/>";
$i++;
}
result:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
Upvotes: 0