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
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 make a series, e.g, 1/2 + 3/4 + 5/6 + 7/8 + 9/10 + 11/12 as a string using loops in php. write now i have written this code:
$output='';
for ($i=0; $i < 6; $i++)
{
$output=$output.($i+1+$i).'/'.($i+2+$i);
if ($i==5)
{
break;
}
else
{
$output=$output.'+';
}
}
echo nl2br("\n4: $output");
output:
1/2 + 3/4 + 5/6 + 7/8 + 9/10 + 11/12
is there any other better approach to do that?
preg_replace('/(\d+) \+ (\d+)/', '$1/$2', implode(" + ", range(1, 12)));
https://www.ideone.com/dKUIwc
With minimum of code it is:
$output = [];
for ($i = 0; $i < 6; $i++) {
$output[] = (2 * $i + 1) . '/' . (2 * $i + 2);
}
echo implode(' + ', $output);
Start loop from 1 and make step of 2 instead of one. Then put every sequence to array and finally implode it with +
$output = [];
for ($i = 1; $i <= 12; $i += 2) {
$output[] = $i . '/' . ($i + 1);
}
echo implode(' + ', $output);
as a string using loops in php. --> display as a string...
Use for loop and modulus operator %. Display first key, a forward slash, then continue the iteration outside that conditional and display the next key, then display a plus sign.
Continue iteration until you evaluate if the value is at the end of the array. Two conditionals inside the loop.
I used a iterator defined as $i as using a foreach loop would start at zero and you would have to do some extra code to get the last value.
$myArray = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16);
$stmt = NULL;
for($i = 0; $i < count($myArray); $i++){
if($myArray[$i] % 2 ){
$stmt .= $myArray[$i]."/";
}else{
if($myArray[$i] !== end($myArray)){
$stmt .= $myArray[$i].' + ';
}else{
$stmt .= $myArray[$i];
}
}
}
OUTPUT:
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
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 a for loop, where $i is 0, and it will run until $i reaches 4. I am trying to make a code that would output numbers in an order like this: 01, 11, 02, 12, 03, 13... etc... Now, the thing is next: when $i is 1, the script should make an order of those number in the boundaries of 1 and 20. When $i is 2, it would be 21 to 40, etc.
I've tried many things (mostly deleted), could not come up with anything that would work the right way.
The inner loop:
for ($j = 0; $j != 10; ++$j)
{
echo $j + 1 + 10 * ($i - 1);
echo $j + 1 + 10 * $i;
}
Try this piece of code;
<?php
$num = 4;
for($i=1;$i<($num + 1);$i++){
$string = "0" . $i . ", 1" . $i;
if($i<$num){
$string .= ", ";
}
echo $string;
}
?>
printf will format your numbers with a leading zero, as specified:
<?php
$format = "%02d ";
for ($i = 1; $i <= 4; $i++) {
$k = 2 * $i - 1;
for ($j = 1; $j <= 10; $j++) {
printf($format, ($k - 1) * 10 + $j);
printf($format, $k * 10 + $j);
}
echo "<br />";
}
?>
You can try:
<?php
$ten = 10;
for ($i = 0; $i<=4; ++$i)
{
echo "0".$i." , ";
echo $ten + $i."<br/>";
}
?>
Only change the range of $i
Thanks