使用c++中的递归函数打印一个数值空心正方形图案



我一直在尝试打印一个正方形的数字模式,如下所示:

12345
2   4
3   3
4   2
54321

但我似乎找不到正确的方法来编写递归函数。我只打印了一个数字三角形,但这个正方形一直在折磨我

#include <iostream> 
using namespace std; 
void print_row(int no, int val) 
{ 
if (no == 0) 
return; 
cout << val << " "; 

print_row(no - 1, val); 
} 

void pattern(int n, int num) 
{ 
if (n == 0) 
return; 
print_row(num - n + 1, num - n + 1); 
cout << endl; 


pattern(n - 1, num); 
} 
int main() 
{ 
int n = 5; 
pattern(n, n); 
} 

输出:

1
2 2
3 3 3
4 4 4 4
5 5 5 5 5

使用递归输出方形图案的代码。这是我尝试打印数字正方形的程度,我不知道如何用升序和降序打印出来。

#include <iostream>
#include <string>
using namespace std;
void line( int row, int num )
{
if ( row < 0 ) return;
char c = row * ( num - row - 1 ) ? ' ' : '*';
cout << '*' << string( num - 2, c ) << "*n";
line( row - 1, num );
}
int main()
{
int n;
cout << "Input side (n > 2): ";   cin >> n;
line( n - 1, n );
return 0;
}
output:
*****
*   *
*   *
*   *
*****

我花时间构建了这两个函数。不过,试着理解它们,你可能正在进行测试,这个主题可能对未来有所帮助。

您只需调用square(n)n是您想要用于平方的数字。

void print_sides(int n, int col) {
if (col == 0) return;
print_sides(n, col - 1);
if(col != 1) cout << col << string(2*(n - 1)-1, ' ') << (n - col) + 1 << "n" ;
}
void square(int n, int col = 0, bool sides = true) {
if (col >= n) {
return;
}
else {
if (sides) {
cout << col + 1 << " ";
square(n, col + 1, true);
}
else {
square(n, col + 1, false);
cout << col + 1 << " ";
}
if (col == n - 1 && sides == true) {
cout << "n";
print_sides(n, col);
square(n, 0, false);
}
}
}

这是解决这个问题的方法之一。

pattern函数打印空心正方形图案,而printSubRows负责生成中间部分。


void printSubRows(int n,int i,int c) {
if (c==n-2) return;
//adjust the space according to your requirements
cout << i << "   " << n-i+1 << endl;
printSubRows(n,i+1,c+1);
}
void pattern(int n) {
//prints the first row
for (int i=1;i<=n;i++) cout << i;
cout << endl;
//recursive function to print the middle part
printSubRows(n,2,0);
//prints the last row
for (int i=n;i>0;i--) cout << i;
cout << endl;
}