注册 登录
编程论坛 C++教室

关于递归的问题..

yshtc 发布于 2007-11-13 23:18, 434 次点击

#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

现在要把print函数写成递归函数...是课本上的习题...本人实在想不出来...望高手指教..谢谢啦
6 回复
#2
duccdd2007-11-13 23:23

void print( int w )

{

if( w == 1 ) {

cout << w << endl;

}

else {

print( w - 1 );

for( int j = 1; j <= w; j++ )

cout << w << ' ';

cout << endl;

}

}

[此贴子已经被作者于2007-11-13 23:24:25编辑过]

#3
aipb20072007-11-13 23:23

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

#4
孤魂居士2007-11-13 23:40
以下是引用aipb2007在2007-11-13 23:23:59的发言:

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

就是强

#5
nuciewth2007-11-13 23:55

void Print(int n,int m)
{
if(m==0)
{
return ;
}
if(n==0)
{
m--;
Print(m,m);
cout<<endl;

}
else
{
Print(n-1,m);
cout<<m<<" ";
}
}

#6
yshtc2007-11-14 12:36

谢谢各位高手啦

#7
醉生梦死2007-11-14 12:46
回复:(aipb2007)void print(int n){ if (n >...
....对递归的过程相当了解了!学习
1