Saturday, February 14, 2015

[PHP] Triangle Asterisk

Problem: Let the user enter a number then use that number to determine the size of the triangle.

Input:
5

Output:
    *
   ***
  *****
 *******
*********

Solution:
$input    = 5; // change this with user input
$space    = $input;
$asterisk = 1;

for($i=0; $i<$input; $i++) {
 echo str_repeat('&nbsp;', --$space);
 echo str_repeat('*', $asterisk);
 echo '<br/>';
 
 $asterisk += 2;
}

Take note that with this solution, you should use a monospace font-family such as Lucida Console or Courier New.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...