方法一:通过数组,先打印外面的*, 再来一个小的打印空格
#include <stdio.h>
int main()
{ int i = 0; int j = 0; int n = 0; int arr[100][100] = { 0 }; while (scanf("%d", &n) != EOF) { for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { arr[i][j] = '*'; } } for (i = 1; i < n - 1; i++) { for (j = 1; j < n - 1; j++) { arr[i][j] = ' '; } } for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { printf("%c ", arr[i][j]); } printf("\n"); } } return 0;
}
方法二:通过找到有*的规律打印
#include <stdio.h>
int main()
{
int n = 0;
while (scanf("%d", &n) != EOF)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (i == 0 || i == (n - 1) || j == 0 || j == (n - 1))
printf("* ");
else
printf(" ");
}
printf("\n");
}
}
return 0;
}