运行结果:
C语言代码:
/* c how to program 习题3.33 */
#include <stdio.h>
// function main begins program execution
int main( void )
{
//定义变量
int side, x, y;
//获取边长
printf("请输入正方形的边长1-20:");
scanf("%d", &side);
//当输入的数值<0或>20时,提示错误并重新获取边长
while(side <= 0 || side > 20){
printf("你的输入有误,请重新输入1-20:");
scanf("%d", &side);
}
//打印正方形
x = y = side;
//判断打印多少列
while( y ){
//判断打印多少行
while( x ){
//判断打印*还是空格
printf("%s", (y == 1 || y == side || x == 1 || x == side) ? "*" : " " );
x--;
}
puts("");
x = side;
y--;
}
}