Two methods of php to realize the printing of hollow pyramid

WBOY
Release: 2016-08-08 09:19:36
Original
2230 people have browsed it
<?php
/*
 *
 *帮朋友做题,写了一个这个空心金字塔的代码。希望和大家交流一下,提出*宝贵建议.
 *
 */
//第一种实现方法
$n=20;//定义总函数
for($i=1;$i<=$n;$i++)//行数循环
 {  
    for($k=1;$k<=$n-$i;$k++)//循环打印出每行前面的空格
	  {  
		  echo "&#160;";
	  }
	//判断并打印出第一行与最后一行的&#39;*&#39;
	if(($i==1)||($i==$n))
	{
		for($j=1;$j<=2*$i-1;$j++)
		  {
			echo &#39;*&#39;;
		  }
		  echo&#39;<br/>';
	}else//循环打印出其他行的'*'与空格
	   {
			echo '*';
			for($k=1;$k<=2*$i-3;$k++)
				{
				echo &#39;&#160;&#39;;
				}
			echo &#39;*&#39;;
			echo &#39;</br>';
	  }
}
//第二种实现空心金字塔(个人感觉代码繁琐,唉。)
$n=20;//定义总函数
for($i=1;$i<=$n;$i++)//行数循环
{  
  for($k=1;$k<=$n-$i;$k++)//循环打印出每行前面的空格
	{
        echo &#39;&#160;&#39;;
    }
  //循环打印出每一行前面空格后的&#39;*&#39;
  if($i==1)//第一行
	{
		echo &#39;*&#39;;
		echo &#39;</br>';
	}else//其它行
		{echo '*';}
  if(($i>=2)&&($i<=$n-1))
	{ //循环打印出第二行到第n-1行的样式
       for($j=1;$j<=2*$i-3;$j++)
		{
	      echo &#39;&#160;&#39;;
	    }
		echo &#39;*&#39;;
		echo &#39;</br>';
    }else if($i==$n)
	   {//循环打印出最后一行的样式
		  for($m=1;$m<=2*$i-2;$m++)//2*$i-2是因为前面多打印一个&#39;*&#39;
		   {
		     echo "*";
		   }
		   echo &#39;</br>';
       }
}
?>
Copy after login

Copyright statement: This article is an original article by the blogger and may not be reproduced without the blogger's permission.

The above introduces the two methods of printing hollow pyramids in PHP, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!