求:把一下程序中的print()函数改写为等价的递归函数

来源:百度知道 编辑:UC知道 时间:2024/05/16 00:49:02
#include <iostream.h>
void print(int w)
{
for(int i=1;i<=w;i++)
{
for(int j=1;j<=i;j++)
cout<<i<<" ";
cout<<endl;
}
}
void main()
{print(5);}

运行显示:
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5

#include <iostream.h>

void print(int w)
{
int n=w;
if(w==1)
cout<<1<<endl;
else
{
n--;
print(n);
for(int i=0;i<w;i++)
cout<<w<<' ';
cout<<endl;
}

}

void main()
{
print(5);
}

void print(int w)
{
int n=w;
if(w!=1)
{
n--;
print(n);
for(int i=0;i>w;w--)
cout<<w<<endl;
}else
{
cout<<1<<endl;
}