So i was asked the following question in an interview. I was able to print the whole xxx thing. but it was not diagonal like the below one. I think it meant to have spaces prints through a loop. Can Someone please help me with this.
How to print the following using php or javascript?? Php would be preferred.
xx
xxxx
xxxxxx
xxxxxxxx
xxxxxxxxxx
what i was able to get was
xx
xxxx
xxxxxx
xxxxxxxx
xxxxxxxxxx
through php for loop.
A solution in Javascript:
function tree(base) {
var i = base,
j;
document.write('<pre>');
while (i--) {
j = i;
while (j--) {
document.write(' ');
}
j = base * 2 - i * 2;
while (j--) {
document.write('X');
}
document.write('<br>');
}
document.write('</pre>');
}
tree(5);
tree(10);
</div>
Simple example
<?php
$char = "x";
$multiplier = 2;
$repeat = 5;
for ($i = 1; $i <= $repeat; $i++) {
$output = null;
for ($j = 1; $j <= $multiplier*$i; $j++) {
$output .= $char;
}
$nbsp = null;
for ($k = 1; $k <= ($repeat-$i)*$multiplier; $k++) {
$nbsp .= " ";
}
echo $nbsp . $output . "<br/>";
}
?>