Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I print integer in triangle form

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

for($i=1;$i<=3;$i++)
 {
    for($j=3;$j>=$i;$j--)
    {
      echo "&nbsp;&nbsp;";
    }
   for($k=1;$k<=$i;$k++)
    {
      echo $k;
    }
   if($i>1)
    {
      for($m=$i; $m>=1; $m--)
         {
           echo $m;
         }
     }      
    echo "<br>";
}

Output of this code is:

   1
  1221
 123321

Where am I going wrong, please guide me.

like image 573
Shubham Verma Avatar asked Feb 26 '14 12:02

Shubham Verma


People also ask

What is Pascal triangle in C?

Pascal's triangle is one of the classic example taught to engineering students. It has many interpretations. One of the famous one is its use with binomial equations. All values outside the triangle are considered zero (0). The first row is 0 1 0 whereas only 1 acquire a space in pascal's triangle, 0s are invisible.


2 Answers

Another integer solution:

$n = 9; 
print str_pad ("&#10029;",$n," ",STR_PAD_LEFT) . PHP_EOL;
for ($i=0; $i<$n; $i++){
    print str_pad ("", $n - $i);
    for ($ii=-$i; $ii<=$i; $ii++){
      if ($i % 2 != 0 && $ii % 2 == 0)
        print "&#" . rand(10025,10059) . ";";
      else print $i - abs($ii) + 1;
    }
    print PHP_EOL;
}

        ✭
        1 
       1✬1 
      12321 
     1❊3✪3✳1 
    123454321 
   1✼3✶5❃5❈3✸1
  1234567654321 
 1✾3✯5✿7❉7✫5✷3✶1 
12345678987654321 

Or if you already have the string, you could do:

$n = 9; $s = "12345678987654321"; $i = 1;

while ($i <= $n)
   echo str_pad ("", $n-$i) . substr ($s,0,$i - 1) . substr ($s,-$i++) . PHP_EOL;
like image 110
גלעד ברקן Avatar answered Oct 05 '22 17:10

גלעד ברקן


Your code should be this:

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

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
like image 21
Code Lღver Avatar answered Oct 05 '22 16:10

Code Lღver