Dylan Caudill
Dylan Caudill

Reputation: 1191

Printing a pattern without a nested loop in PHP

The output to my code should be:

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

I'm currently using this code with a nested for loop to get the result.

for($lineNumber=1;$lineNumber<=5;$lineNumber++) {
    for($starCount=1;$starCount<=$lineNumber;$starCount++)         {
            echo("*");
    }
        echo("<br />");
}

I need to be able to get the same result without the nested for loop, and I'm stumped. The only thing I want to use is a single for loop. Nothing else. No ifs, switches, or other loops.

Thanks!

Upvotes: 2

Views: 942

Answers (5)

user20656632
user20656632

Reputation:

Here is recursion version of it.

function inner($num)
{
    if ($num == 0)
        return;
    echo "*";
 
    inner($num - 1);
}
 
function outer($n, $i)
{
    if ($n == 0)
        return;
    inner($i);
    echo "<br/>";
    outer($n - 1, $i + 1);
}
 
$n = 5;
outer($n, 1);

Upvotes: 1

Satyandra Shakya
Satyandra Shakya

Reputation: 371

As of your requirement, that is fine to use with concat the string but what if string is not same as previous? here is solution for each patterns without any loop.

$i = 0;
a:
if($i <= 5){
    $j = 1;
    b:
    if($j<=$i){
        echo $i;
        $j++;
        goto b;
    }
    echo "<br/>";
    $i++;
    goto a; 
}

This will print

1
22
333
4444
55555

You can make any pattern like this.

Upvotes: 0

These are some examples of drawing a pyramid:

function print($n)
{
    //example 1
    for ($x = 1; $x <= $n; $x++) {
        for ($y = 1; $y <= $x; $y++) {
            echo 'x';
        }
        echo "\n";
    }

    // example 2
    for ($x = 1; $x <= $n; $x++) {
        for ($y = $n; $y >= $x; $y--) {
            echo 'x';
        }
        echo "\n";
    }

    // example 3

    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";
    }


}

Upvotes: 0

Amir Hossein Baghernezad
Amir Hossein Baghernezad

Reputation: 4095

Use this:

for($lineNumber=1;$lineNumber<=5;$lineNumber++) {
    echo str_repeat("*",$lineNumber);
    echo("<br />");
}

Upvotes: 2

CollinD
CollinD

Reputation: 7573

$str = '';
for($lineNumber=1;$lineNumber<=5;$lineNumber++) {
    $str = $str . '*';
    echo $str;
    echo("<br />");
}

Using this string accumulator removes the need for a second loop.

Upvotes: 5

Related Questions