Rishi Kulshreshtha
Rishi Kulshreshtha

Reputation: 1888

Print pattern of asterisks with n per line, decrementing to 1, then back to n

If the input is 3 then the output should be

***
**
*
**
***

In the same way, if the accepted values is 5 then the output should be

*****
****
***
**
*
**
***
****
*****

This is what I've done but its not correct

<?php
echo "<pre>";
for ($row = 1; $row <= 5; $row++)
{
    for ($col = 1; $col <= 6 - $row; $col++)
    {
        echo '*';
    }

    echo "\n";
}
for ($row = 1; $row <= 5; $row++)
{
    for ($col = 1; $col <= $row; $col++)
    {
        echo '*';
    }

    echo "\n";
}
?>

Upvotes: 3

Views: 1598

Answers (3)

sjagr
sjagr

Reputation: 16502

What's with the nested for loops?

$lineBreak = "\r\n"; // This may need to be <br /> if carriage returns don't show in <pre>
$maxNum = 5;
echo '<pre>';
for ($i = $maxNum; $i > 0; $i--) {
    echo str_repeat('*', $i) . $lineBreak;
}
for ($i = 2; $i <= $maxNum; $i++) {
    echo str_repeat('*', $i) . $lineBreak;
}
echo '</pre>';

For fun, to eliminate one more for loop:

$lineBreak = "\r\n";
$maxNum = 5;
$out = '*';
for ($i = 2; $i <= $maxNum; $i++) {
    $out = str_repeat('*', $i) . $lineBreak . $out . $lineBreak . str_repeat('*', $i);
}
echo '<pre>' . $out . '</pre>';

Note that this code wouldn't be valid with $maxNum < 1.

To fetch a value from the user replace the $maxNum line with...

$maxNum = $_GET['maxNum'];

and load the page using scriptname.php?maxNum=5

Upvotes: 4

Parris Varney
Parris Varney

Reputation: 11488

I think your professor is looking for recursion here..

Something like this should work -

function stars($num) {
  echo str_repeat('*', $num)."\n";

  if ($num > 1) {
    stars($num - 1);
    echo str_repeat('*', $num)."\n";
  }
}

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324760

A one-liner for you :p

echo implode("\n",array_map(function($n) {return str_repeat("*",$n);},array_merge(range($input,1),range(2,$input))));

Broken down:

  • Create a range of numbers from "input" down to 1
  • Create a range of numbers from 2 up to "input" (prevents duplicate "1")
  • Merge the two ranges, resulting in the "down-then-up" list
  • Replace each item in the array with the appropriate number of stars
  • Glue them together on new lines.

Note that you may need <br /> instead of \n to output in a browser.

Upvotes: 2

Related Questions