Stuck with the number pattern printing logic. Let me know what i am doing wrong as my file is simply going on execution without giving me a pattern.
My Code --
<?php
$num = 4;
for( $j=1 ; $j <= $num ; $j++ )
{
for( $i=$j ; $i < $num-1 ; $i++ )
{
echo " ";
}
for( $j ; $j >= 1 ; $j-- )
{
echo $j." ";
}
echo "<br />";
}
Pattern to achieve --
1
21
321
4321
UPDATE
After applying new changes following are the screenshots ---
for ($i = 1; $i <= 4; $i++) {
echo str_pad(implode('', range($i, 1)), 4, ' ', STR_PAD_LEFT) . '<br />';
}
Right aligned using CSS
echo '<div style="text-align:right;">';
for ($i = 1; $i <= 4; $i++) {
echo implode('', range($i, 1)) . '<br />';
}
echo '</div>';
Your error is in the last for, that should not exist since you are already looping.
And create a new variable which will hold the printed text for the next increment.
<?php
$num = 4;
$wrap = '';
for( $j=1 ; $j <= $num ; $j++ )
{
for( $i=$j ; $i < $num ; $i++ )
{
echo " ";
}
echo $wrap = $j.$wrap;
echo "<br />";
}
?>
The fundamental reason is that a browser wont render multiple spaces only the first one, you can overcome this by using the non breaking space html entity   in place of spaces.
Soooo, If you want your actual pattern to look like:
1
21
321
4321
And not like:
1
21
321
4321
Use   (Edit: Tho actually use [space] as just 1 seems to not compensate for the width of the 1 char vs 4)
<?php
$num = 4;
$result = array();
foreach(range($num,1) as $i){
$result[] = str_repeat(' ',$num-$i).implode('',range($i,1)).'<br />';
}
echo implode('',array_reverse($result));
?>
Or you could use a <pre> tag like:
<?php
$num = 4;
$result = array();
foreach(range($num,1) as $i){
$result[] = str_repeat(' ',$num-$i).implode('',range($i,1)).PHP_EOL;
}
echo '<pre>'.implode('',array_reverse($result)).'</pre>';
?>
As it is right now, the problem lies in your third (or second nested) for loop.
You can't just reuse $j as a counter here, since $j is still being actively used in the encompassing for loop. Substitute that for loop with:
for( $k = $j ; $k >= 1 ; $k-- )
{
echo $k." ";
}
Here is the code for your program, You can go to Develepor hell for more such pattern
// Outer look for line change
for ($i = 1; $i<=5; $i++) {
// Loop added for spacing
for ($s = $i; $s<=10-$i; $s++) {
echo " ";
}
// Inner loop for printing required pattern
for ($j = $i; $j>=1; $j--) {
echo $j;
}
echo '</br>';
}
// Here is the code for your program,
// Pattern - 1
$num = 4;
// to print no. of rows
for( $i=1 ; $i <= $num ; $i++ )
{
// To print white space
for( $j=1 ; $j <= $num-$i ; $j++ )
{
echo "0";
}
// To print pattern
for( $z= $i ; $z>=1 ; $z-- )
{
echo $z;
}
// To print new line
echo "<br />";
}
==>> Output
0001
0021
0321
4321
//===================================================================//
Pattern - 2
$z=1;
$n=3;
# no of rows
for($i=1;$i<=$n;$i++)
{
# to check even or odd
if($i%2 == 0)
{
# main logic to display in reverse order // right to left
$z = ($z+$n) -1;
$a = $z;
for($j=1;$j<=$n;$j++)
{
echo $z--;
}
$z = $a+1;
}
else
{
# display data left to right
for($j=1;$j<=$n;$j++)
{
echo $z++;
}
}
echo "<br/>";
}
==>> Output
123
654
789
Your issue appears to be that you are printing your output into an HTML document which condenses multiple spaces as its default behavior. See "Why does HTML require that multiple spaces show up as a single space in the browser?" To "preserve" whitespaces while printing, use the <pre> tag.
I'll add a math-based solution instead of multiple iterated function calls and multiple loops (inspired by my explained answer here). Once your number limit gets higher than 9, I don't know if my output will align with your desired output.
Effectively, I use printf() to left-pad every line with spaces to the same max length. Each successive number prints the integer as many times as its value.
Code: (Demo)
$num = 4;
echo "<pre>";
for ($i = 1; $i <= $num; ++$i) {
printf("% {$num}d<br>", (10 ** $i - 1) / 9 * $i);
}
HTML Output (click on the eye icon in the demo link to switch to HTML mode):
1
22
333
4444
For comparison these also work inside of the for() loop (and offer a more intuitive result above 9):
printf("% {$num}d<br>", str_repeat($i, $i));
Or
echo str_repeat(' ', $num - $i) . str_repeat($i, $i) . "<br>";
Related
I want to give n as a input and get a pattern like this.
pattern If n = 4
1
222
33333
4444444
33333
222
1
What is the perfect way to achieve this?
I have tried. But my code is not good! Is there any way to do this with less and clear code!?
echo '<pre>';
$n=4;
for ($i=1; $i <= $n*2-1; $i++) {
if($n<$i){ //bottom part
$scount=$i-$n;
$iterator = 0;
while($iterator != $scount){
$iterator++;
echo ' ';
}
$num = ($n*2)-$i;
$loop = $num*2-1;
$iterator = 0;
while($iterator != $loop){
$iterator++;
echo $num;
}
}elseif ($n==$i){ // middle part
$loop = $i*2-1;
$iterator = 0;
while ($iterator != $loop) {
$iterator++;
echo $i;
}
}else{ //top part
$scount = $n-$i;
$iterator=0;
while ($iterator != $scount) {
$iterator++;
echo ' ';
}
$loop = $i*2-1;
$iterator = 0;
while($iterator != $loop){
$iterator++;
echo $i;
}
}
echo "<br>";
}
?>````
On a similar line to the other answers, but this builds a string with the output. This allows it to build each of the repeating lines in the loop and add it to the start and end of the result string. This means the loop is only run $n-1 times (plus the first line which sets the middle line)...
$n=4;
$output = str_repeat("$n", (2*$n)-1).PHP_EOL;
for ( $i = $n-1; $i>0; $i-- ) {
$line = str_repeat(' ', $n-$i).str_repeat("$i", (2*$i)-1);
$output = $line.PHP_EOL.$output.$line.PHP_EOL;
}
echo $output;
Two for loops which repeats the number of spaces needed and characters.
$n = 4;
for($i=1;$i<=$n;$i++){
echo str_repeat(" ", $n-$i+1) . str_repeat($i, $i*2-1) . "\n";
}
for($i=$n-1;$i>0;$i--){
echo str_repeat(" ", $n-$i+1) . str_repeat($i, $i*2-1) . "\n";
}
https://3v4l.org/1hK3s
You can solve this by noticing the longest line is the one with the max value of n, and that has 2*n-1 n's in it. All other lines need spacing to make them line up with that one which will be half the difference between the number of n's on that line and the number on the longest line. str_repeat is a good way of generating those repeated strings:
echo "<pre>\n";
$n=4;
$max_length = $n * 2 - 1;
for ($i = 1; $i <= $n * 2 - 1; $i++) {
$this_n = ($i <= $n) ? $i : $n * 2 - $i;
$num_ns = $this_n * 2 - 1;
echo str_repeat(' ', ($max_length - $num_ns) / 2);
echo str_repeat("$this_n", $num_ns);
echo "\n";
}
echo '</pre>';
Output:
<pre>
1
222
33333
4444444
33333
222
1
</pre>
Demo on 3v4l.org
Please give me the solution for to print a triangle in stars pattern using php language. I used only 2 for loops to finish this.
*
***
*****
*******
Here is my code
<?php
for($a=1;$a<=7;$a++)
{
for($b=1;$b<=$a;$b++)
{
echo " *";
}
echo "<br/>";
}
echo " ";
?>
Please help me out.
<?php
for($i=0; $i < 5 ; $i++)
{
echo"<br>";
for($j=0; $j <=$i ; $j++){
echo "*" ;
}
}
?>
For more php Star patterns
This will work, still uses two for loops:
echo "<pre>";
$stars = "*";
for($a=1; $a<=4; $a++)
{
$spaces = "";
for($b = (5 - $a); $b>1; $b--)
{
$spaces .= " ";
}
echo $spaces . $stars . $spaces;
$stars .= "**";
echo "<br/>";
}
echo "</pre>";
I've used an accumulator for $stars, it starts from one star, an adds two stars at each iteration, and one accumulator for $spaces, that gets reset at each main for iteration.
The triangle is build top to bottom using one layer at a time.
One layer is made of spaces, stars and spaces again
for($x = 0; $x < $n; $x++) {
for($y = 0; $y < $n - $x; $y++) {
echo ' ';
}
for($z = 0; $z < $x * 2 +1; $z++) {
echo 'x';
}
echo "\n";
}
Draw a staircase of height N like this:
#
##
###
####
#####
######
Staircase of height 6, note the last line should have zero spaces.
My solution does not work correctly
function draw($size)
{
for ($i = 1; $i <=$size ; $i++)
{
$spaces = $size-$i;
while ($spaces)
{
echo " ";
$spaces--;
}
$stairs = 0;
while ($stairs < $i)
{
echo "#";
$stairs++;
}
echo "<br/>";
}
}
draw(6);
//output
#
##
###
####
#####
######
It is not printing the spaces, I tried \n, PHP.EOL still it didn't work. Any suggestions?
Although other solutions are all good , here is my code as well.
$max=5;
for ( $i =1 ; $i<=$max;$i++) {
for ( $space = 1; $space <= ($max-$i);$space++) {
echo " ";
}
for ( $hash = 1; $hash <= $i;$hash ++ ) {
echo "#";
}
echo "\n";
}
//PHP
$n = 6; // Number of rows.
for($i=1;$i<=$n;$i++){
echo str_repeat(' ', $n-$i) . str_repeat('#', $i);
echo '\n';
}
for(var i = 0; i < n; i++)
{
var s = "";
for(var j = 0; j < n; j++)
{
if(n - i - 2 < j)
{
s += "#";
}
else
{
s += " ";
}
}
console.log(s);
}
for ($i=0; $i<$n; $i++){
for ($j=0; $j<$n; $j++){
if($i+$j>$n-2){
echo "#";
} else {
echo " ";
}
if($j==$n-1 && $i+$j<$n*2-2){ //The second part is to dont break the last line
echo "\n";
}
}
}
Here's another solution:
$int = 7;
for($i = 1; $i<=$int; $i++){
printf('%1$s%2$s%3$s',str_repeat(" ",$int-$i),str_repeat("#",$i),"\n");
}
From official PHP documentation:
str_repeat
$n = 6;
for ($i = 0; $i < $n; $i++) {
$pad = 1;
for ($space = 0; $space < $n-$i-1; $space++) {
$pad++;
}
echo str_pad('#', $pad,' ',STR_PAD_LEFT);
for ($j = 0; $j < $i; $j++) {
echo '#';
}
echo '<br>';
}
Took me a while but finally I manage to do it following OFC (A. Sharma) Example.
<?php
$handle = fopen("php://stdin","r");
$n = intval(fgets($handle));
for ($rows = 0; $rows < $n; $rows++) {
for ($columns = 0; $columns < $n - $rows - 1; $columns++) {
echo " ";
}
for ($columns = 0; $columns < $rows + 1; $columns++) {
echo "#";
}
echo "\n";
}
?>
Use PHP functions range() and str_repeat() for an elegant solution:
function staircase($n){
foreach (range(1, $n) as $i)
print( str_repeat(' ',$n-$i).str_repeat('#',$i)."\n");
}
demo
Check if n is between 0 and 101 ( 0 < n <= 100)
Loop through each row
2.1 print spaces according to the last item position
2.2 print the items
Separate rows
The code below explains everything...
function staircase($n) {
// check if n is between 0 and 101 (0 < n <=100)
if( 0 < $n && $n > 100 ) {
} else {
// Loop through each row
for($i = 1; $i <= $n; $i++) {
// print spaces according to the last item position
$si = 1;
while( $si <= ($n - $i)){
print(" ");
$si++;
}
// print the items
for($j = 1; $j <= $i; $j++) {
print("#");
}
// separate rows
print("\n");
}
}
}
Output: For n = 6
#
##
###
####
#####
######
After playing around with the code and trying/failing couple of times I finally got it right. Notice how in order to print the space and new line I am using "\n". Previous "<br/>" and " " for space didn't work.
Break line will come out of the loop every row number. So if we have $n=4 then every 4 spaces after break line will be echoed.
I have made 2 loops to fill in all fields in the staircase.
The tricky part here is to have them right aligned. This is where if statement comes in place.
Reference link:
Hackerrank Challenge
// Complete the staircase function below.
function staircase($n) {
for($i=1; $i<=$n; $i++){
for($j=1; $j <= $n; $j++){
if( ($n - $i) < $j ){
echo "#";
}else{
echo " ";
}
}
echo "\n";
}
}
Try This
$n=6;
for($i=1;$i<=$n;$i++){
for($spaces=1;$spaces<=($n-$i);$spaces++){
echo " ";
}
for($staires=0;$staires<$i;$staires++){
echo "#";
}
echo "\n";
}
This worked for me
$n = 6;
function staircase($n) {
for($i=1; $i <= $n; $i++){
for($j=1; $j <= $n; $j++){
if($j > $n-$i){
echo "#";
}else{
echo " ";
}
}
echo "\n";
}
}
Use print(' '), if you want to go to next line put print(' ')."\n"
JavaScript:
Solution:
function StairCase(n){
let x = [];
for(let i = 0; i<n; i++){
while(x.length < n){
x.push(" ");
}
x.shift();
x.push("#");
console.log(x.join(''));
} } //StairCase(6)
I want to print integer in triangle form which look like this
1
121
12321
I tried this but I do not get the actual result
for($i=1;$i<=3;$i++)
{
for($j=3;$j>=$i;$j--)
{
echo " ";
}
for($k=1;$k<=$i;$k++)
{
echo $k;
}
if($i>1)
{
for($m=$i; $m>=1; $m--)
{
echo $m;
}
}
echo "<br>";
}
Output of this code is:
1
1221
123321
Where am I going wrong, please guide me.
Another integer solution:
$n = 9;
print str_pad ("✭",$n," ",STR_PAD_LEFT) . PHP_EOL;
for ($i=0; $i<$n; $i++){
print str_pad ("", $n - $i);
for ($ii=-$i; $ii<=$i; $ii++){
if ($i % 2 != 0 && $ii % 2 == 0)
print "&#" . rand(10025,10059) . ";";
else print $i - abs($ii) + 1;
}
print PHP_EOL;
}
✭
1
1✬1
12321
1❊3✪3✳1
123454321
1✼3✶5❃5❈3✸1
1234567654321
1✾3✯5✿7❉7✫5✷3✶1
12345678987654321
Or if you already have the string, you could do:
$n = 9; $s = "12345678987654321"; $i = 1;
while ($i <= $n)
echo str_pad ("", $n-$i) . substr ($s,0,$i - 1) . substr ($s,-$i++) . PHP_EOL;
Your code should be this:
for($i=1;$i<=3;$i++)
{
for($j=3;$j>$i;$j--)
{
echo " ";
}
for($k=1;$k<$i;$k++) /** removed = sign*/
{
echo $k;
}
if($i>=1) /**added = sign*/
{
for($m=$i; $m>=1; $m--)
{
echo $m;
}
}
echo "<br>";
}
Try this.
Details:
Your loop is not proper as in case of for($k=1;$k<=$i;$k++), this will print the
repeated number when check the condition for less then and again for equals to.
So remove the equals sign.
reason to add the eqaul sign in if($i>=1) is that the first element will not print if there will not be equals as first it will be print by for loop from where removed the equal sign.
Your output will be this:
1
121
12321
For all the x-mas lovers:
$max = 9; # can be 2 .. 9
for($i = 1; $i <= $max; $i++) {
$line = (str_pad('', $max - $i));
for($ii = 1; $ii <= $i; $ii++) {
$line .= $ii;
}
for($ii = $i-1; $ii > 0; $ii--) {
$line .= $ii;
}
echo $line . PHP_EOL;
}
Output:
1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321
Amazing what computers are able to achieve nowadays! Isn't it?
A little late to the party, but here's yet another solution that uses a "for" loop with two initialization variables and a ternary-based incrementer/decrementer. It's an unorthodox use of a "for" loop, but it's still perfectly valid and arguably makes the code more elegant and easier to follow. I chose to add space before and after each semicolon and omit all other space inside the parentheses so it's easier to visualize each of the three pieces of the "for" loop (initialization, condition, increment/decrement):
$count = 9;
echo "<pre>";
for ($i=1; $i<=$count; $i++) {
echo str_pad("",$count-$i," ",STR_PAD_LEFT);
for ( $j=1,$up=true ; $j>0 ; $up?$j++:$j-- ) {
echo $j;
if ($j==$i) {$up = false;}
}
echo "<br>";
}
echo "</pre>";
Output:
1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321
I'm trying to echo stars and zero like the pattern below
*
***0
******00
**********000
The length of the asterisks grows by an increasing factor (in a ballooning fashion) -- the previous number of asterisks plus the current iteration number.
iteration 1: 1 (0 + 1)
iteration 2: 3 (1 + 2)
iteration 3: 6 (3 + 3)
iteration 4: 10 (6 + 4)
iteration 5: 15 (10 + 5)
etc
The length of the zeros increases by a static factor.
iteration 1: 0
iteration 2: 1
iteration 3: 2
iteration 4: 3
iteration 5: 4
etc
My code currently looks like this:
for ($i=0; $i<=10; $i++)
{
echo "*";
for ($j=0; $j<$i; $j++)
{
echo "*";
}
for ($z=0; $z<$i; $z++)
{
echo "0";
}
echo "</br>";
}
However I'm getting this result:
*
**0
***00
****000
*****0000
******00000
The number of stars is indicated by triangle numbers, 1, 1+2, 1+2+3. You want to increment your inner loop max value by $i with every iteration:
$k = 0;
for ($i=1; $i<=10; $i++)
{
$k += $i;
for ($j=1; $j<=$k; $j++)
{
echo "*";
}
...
}
This is also a good case where your loops should be initialized with 1 rather than 0, because it is more intuitive. 0-based loops work best when you are working with arrays.
I think something like this is more efficient; you can cache the current sequence of stars and zeros.
$cache_star = "";
$cache_zero = "";
for ($i=1; $i<=10; $i++)
{
for ($j=1; $j<=$i; $j++)
{
$cache_star .= "*";
}
echo $cache_star.$cache_zero;
$cache_zero .= "0";
}
Here's what I got:
for($i = 1; $i != 5; $i++)
{
$triangle = (0.5 * $i) * ($i + 1);
echo str_repeat('*', $triangle) . str_repeat('0', $i) . PHP_EOL;
}
Uses the formula 0.5n(n + 1) - the triangle numbers formula.
Example output:
*0
***00
******000
**********0000
I quite like #jordandoyle's approach, but I correct the zeros pattern by subtracting 1 from $i in the second str_replace()..
Code: (Demo)
$number = 5;
for ($i = 1; $i <= $number; ++$i) {
echo str_repeat('*', $i * .5 * ($i + 1))
. str_repeat('0', $i - 1)
. PHP_EOL;
}
Output:
*
***0
******00
**********000
***************0000
If this answer lacks significant uniqueness versus an earlier answer, I'll include a recursive approach as well (instead of a classic loop).
Code: (Demo)
function printLines($i, $lines = [], $newline = PHP_EOL) {
if ($i > 0) {
array_unshift(
$lines,
str_repeat('*', $i * .5 * ($i + 1))
. str_repeat('0', $i - 1)
);
printLines(--$i, $lines);
} else {
echo implode($newline, $lines);
}
}
printLines(5);
You can even copy the previous line and insert it into the middle of the next line to form the desired pattern. This is the functional-style equivalent of #CoertMetz's nested loop technique.
Code: (Demo)
$number = 5;
$line = '';
for ($i = 1; $i <= $number; ++$i) {
echo (
$line = str_repeat('*', $i)
. $line
. ($i > 1 ? '0' : '')
)
. PHP_EOL;
}
All above techniques deliver the same result.
Smells like homework... But ok, what about this:
$star = "*";
echo $star."\n";
for ($i=0; $i<=10; $i++)
{
$star = $star."**";
echo $star;
echo str_repeat("0", $i+1);
echo "\n";
}
Outcome:
*
***0
*****00
*******000
*********0000
***********00000
*************000000
***************0000000
*****************00000000
*******************000000000
*********************0000000000
***********************00000000000
Demo:
http://sandbox.onlinephpfunctions.com/code/583644f782005adb9e018b965cbbdefaf63c7c79