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
Related
How to print this Pattern?
$number = 5;
for ($i=1; $i <= $number ; $i++) {
for ($j=$i; $j >= 1;$j--){
echo "0";
}
echo "\n";
}
Prints
0
00
000
0000
00000
I've tries like this, but i'm confused to print star and Zero char
for ($i=1; $i <= $number ; $i++) {
$sum = 0;
for ($j=$i; $j >= 1;$j--){
$sum +=$j;
}
echo $i ." => " .$sum ."\n";
}
Prints
1 => 1
2 => 3
3 => 6
4 => 10
5 => 15
You can use str_repeat to generate the strings of required length. Note that for triangular numbers (1, 3, 6, 10, 15, ...) you can generate the i'th number as i(i+1)/2:
$number = 5;
for ($i = 1; $i <= $number; $i++) {
echo str_repeat('*', $i * ($i + 1) /2) . str_repeat('0', $i) . PHP_EOL;
}
Output:
*0
***00
******000
**********0000
***************00000
Demo on 3v4l.org
For a more literal generation of the triangular part of the output (i.e. sum of the numbers from 1 to i), you could use this code which adds $i *'s and 1 0 to the output on each iteration:
$line = '';
$number = 5;
for ($i = 1; $i <= $number; $i++) {
$line = str_repeat('*', $i) . $line . '0';
echo $line . PHP_EOL;
}
Output:
*0
***00
******000
**********0000
***************00000
Demo on 3v4l.org
Here is another way, which uses a more literal reading of the replacement logic. Here, I form each subsequent line by taking the previous line, and adding the line number amount of * to the * section, and then just tag on a new trailing zero.
$line = "*0";
$max = 5;
$counter = 1;
do {
echo $line . "\n";
$line = preg_replace("/(\*+)/", "\\1" . str_repeat("*", ++$counter), $line) . "0";
} while ($counter <= $max);
This prints:
*0
***00
******000
**********0000
***************00000
The number of zeros are equal to $i in the for loop. So we just need to calculate the number of stars and then simply do a str_repeat
$count = 5;
for ($i=1; $i <= $count; $i++) {
$stars = 0;
for($j=1; $j <= $i; $j++) {
$stars = $stars + $j;
}
echo str_repeat('*', $stars).str_repeat('0', $i)."\n";
}
Output:
*0
***00
******000
**********0000
***************00000
$line = '';
for ($i = 1; $i <= 5; $i++) {
$line = str_repeat('*', $i) . $line . '0'; // **str_repeat()** --> getting string length
echo $line . PHP_EOL; // **PHP_EOL** ---> represents the endline character.
}
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
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>";
i have:
# = 1
# = 0,5
% = 0
max = 10
for example if i have: 3 then should show me:
###$$$$$$$
if i have 3,5 :
####$$$$$$
etc
if i have 3,99 then = 3,5
if i have 3,49 then = 3,0
etc
how can i use this with foreach or for?
for whole number i can make:
$number = 8;
$one = 10 - $number;
$three = 0 + $number;
and
for($i=1;$i <= $one){
echo "#";
}
for($i=1;$i <= $three){
echo "$";
}
but how is the best solution if $number = 3,57
If I've understood what you're after, this should do what you want:
<?php
function printItOut($number) {
$s = '';
for ($i = 0; $i < 10; $i++) {
if ($i < $number%10) {
$s .= '#';
} else if ($i < ($number+0.5)%10) {
$s .= '#';
} else {
$s .= '$';
}
}
return $s;
}
echo printItOut(3.49), "\n";
echo printItOut(3.5), "\n";
echo printItOut(3.99), "\n";
echo printItOut(4), "\n";
Outputs:
###$$$$$$$
####$$$$$$
####$$$$$$
####$$$$$$
Inside the for loop, I using the modulus operator to find the integer remainder of dividing $number by 10. So 3%10 gives a result of 3, 3.49%10 also results in 3.
In the first 'else if' block, I'm checking whether the number is 0.5 or more, since (3.49+0.5) is 3.99, and 3.99%10 is 3; but 3.5+0.5 is 4, and 4%10 is 4.