Output Graphics with 2D Array
train of thought
- Apply for a two-dimensional array (fixed size)
- Populate a 2D array sequentially based on a condition
- Fill the last character of each line with '\0' as the end of the string
- Use printf %s to output the content (string) of each line
topic:
Title description:
Input a height h, output a trapezoid with height h and upper base length h.
Input:
an integer h (1 ≤ h ≤ 1000)
Output:
Trapezoid corresponding to h.
Sample input:
4
Sample output:
Analysis: when h=4, the first line has h asterisks, the second line has h+2 asterisks...the fourth line has h+6 asterisks, and the total number of spaces and asterisks in each line is 3h-2
According to this rule, the characters can be filled in the two-dimensional array and printed.
two implementations
#include <stdio.h>
char arr[1000][3000]; //定义一个全局数组
//二维数组处理图案模拟问题
void fun(){
int h;
scanf("%d", &h);
for(int i = 0 ; i < h; i++){
//在每一行填充空格
for(int j = 0;j < 3*h - 2;j++){
arr[i][j] = ' ';
}
}
for(int i = 0; i < h;i++){
//在每一行填充*
for(int j = 2*h - 2*i - 2; j < 3*h - 2;j++){
arr[i][j] = '*';
}
}
for(int i = 0 ; i < h; i++){
//将每一行字符串打印输出
for(int j = 0;j < 3*h - 2;j++){
printf("%c", arr[i][j]);
}
printf("\n");
}
}
void fun_2(){
//使用字符串形式输出
int h;
scanf("%d", &h);
for(int i = 0 ; i < h; i++){
//在每一行填充空格
for(int j = 0;j < 3*h - 2;j++){
arr[i][j] = ' ';
}
arr[i][3*h-2] = '\0';
}
for(int i = 0; i < h;i++){
//在每一行填充*
for(int j = 2*h - 2*i - 2; j < 3*h - 2;j++){
arr[i][j] = '*';
}
}
for(int i = 0 ; i < h; i++){
//将每一行字符串打印输出
printf("%s\n", arr[i]);
}
}
int main(){
// fun();
// fun_2();
return 0;
}