How can I print integer in triangle form

前端 未结 4 2296
时光取名叫无心
时光取名叫无心 2021-02-13 22:20

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



        
4条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-13 22:56

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

    Output:

            1
           121
          12321
         1234321
        123454321
       12345654321
      1234567654321
     123456787654321
    12345678987654321
    

提交回复
热议问题