How to print this pyramid pattern?

1 points by shivajikobardan a year ago

https://imgur.com/a/aYD4tcX

I want this pattern, what's the logic behind this one? There are lots of blogs online that show code but not teach technique. Share any blogs that you know that teach the logic behind it as well. At i=1, j=5 should be printed as star, rest as white spaces

At i=2, j=4,6…

At i=3, j=3,5,7….

At i=4,j=2,4,6,8…

At i=5, j=1,3,5,7,9…

How do I convert this into logic?

Minor49er a year ago

The number of rows that you have will be your X offset (or in other words, the number of spaces that you start a line with) before you draw a repeating pattern of stars. Each iteration, you subtract from the offset. Here's a simple example in PHP:

    <?php
    
    $maxStars = 5;
    
    for ($stars=1; $stars <= $maxStars; $stars++) {
        $offset = $maxStars - $stars;
        echo str_repeat(' ', $offset);
    
        for ($starCounter = 0; $starCounter < $stars-1; $starCounter++) {
            echo '* ';
        }
        echo "*\n";
    }
pwg a year ago

> How do I convert this into logic?

By looking for the pattern in your statements above.

There is a pattern there, compare each line to the one above and below, and think about what those numbers mean if plotted onto a 2D grid.

Once you see the pattern, then the logic is a straightforward outgrowth of the pattern from one line to the next.

shivajikobardan a year ago

for (i = 1; i <= 5; i++) { for (space = 1; space <= 5 - i; space++) { document.write("0"); } for (j = 1; j <= i; j++) { document.write("X0"); } document.write("<br>"); }