Reputation:
I am trying to get this kind of matrix:
1 0 0 0 5
0 2 0 4 0
0 0 3 0 0
0 2 0 4 0
1 0 0 0 5
and here is the code:
$n = 5;
$flag = 0;
for($i=1; $i<=$n; $i++){
for($j=1; $j<=$n; $j++){
if($i == $j){
echo "$i ";
}else{
echo "0 ";
}
if($j == $n - $flag){
echo $n - $flag." ";
$flag++;
}
}
echo "</br>";
}
the output is:
1 0 0 0 0 5
0 2 0 0 4 0
0 0 3 3 0 0
0 0 2 0 4 0
0 1 0 0 0 5
there is something wrong in the middle. I think it is because two for loops overlap there. How to fix thiis?
Upvotes: 0
Views: 51
Reputation:
The reason isn't an overlap in the loops. Its an overlap of the two if
statements.
In the inner loop, you always print 6 things.
for($j=1; $j<=$n; $j++){
if($i == $j){ // <--- This will always print in each iteraton (i.e 5 times)
echo "$i ";
}else{
echo "0 ";
}
if($j == $n - $flag){ // <--- This will print once in the loop (the 6th extra)
echo $n - $flag." ";
$flag++;
}
}
Since $j
is equal to $flag
, you don't need to keep track of it.
Change it to this (Check it on ideone):
for($j=1; $j<=$n; $j++){
if($i == $j){
echo "$i ";
} elseif($j == $n - $i + 1){
echo $n - ($i-1)." ";
} else {
echo "0 ";
}
}
Upvotes: 1
Reputation: 1362
Try this code to output the array you want:
$n = 6;
for($i=1; $i<$n; $i++){
for($j=1; $j<$n; $j++){
if($i == $j){
echo "$i ";
} else if ($j == $n - $i) {
echo $n - $i ." ";
} else {
echo "0 ";
}
}
echo "</br>";
}
Upvotes: 2