How can I print integer in triangle form

前端 未结 4 2376
时光取名叫无心
时光取名叫无心 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:38

    Your code should be this:

    for($i=1;$i<=3;$i++)
     {
        for($j=3;$j>$i;$j--)
        {
          echo "  ";
        }
       for($k=1;$k<$i;$k++) /** removed = sign*/
        {
          echo $k;
        }
       if($i>=1) /**added = sign*/
        {
          for($m=$i; $m>=1; $m--)
             {
               echo $m;
             }
         }      
        echo "
    "; }

    Try this.

    Details:

    1. Your loop is not proper as in case of for($k=1;$k<=$i;$k++), this will print the repeated number when check the condition for less then and again for equals to. So remove the equals sign.

    2. reason to add the eqaul sign in if($i>=1) is that the first element will not print if there will not be equals as first it will be print by for loop from where removed the equal sign.

    Your output will be this:

       1
      121
     12321
    

提交回复
热议问题