六边形图案的 C 程序
我们得到一个整数 n,任务是生成六边形图案并显示最终输出。
示例
Input-: n=5 Output-:
Input-: n = 4 Output-:
我们在给定程序中使用的方法如下 −
- 从用户输入数字 n
- 将整个图案分为三个部分,即上部、中部和下部启动循环 i,从 i 到 0 并 i 小于 n 打印图案的上部,并一直递增 i 的值启动循环 m,从 m 到 0 并 m 小于 n-2 打印图案的中部,并一直递增 m 的值启动循环 h,从 h 到 res 并 h 大于 0 打印图案的下部,并一直递减 h 的值一直使用空格打印 *。
算法
START Step 1-> declare function to print hexagonal pattern void pattern(int n) Declare and set int len = 2 * n - 1 Loop For int i = 0 and i < n and i++ declare and set int temp = i + n Loop For int k = 0 and k < temp and k++ IF ((k == n + i - 1) || (k == n - i - 1)) print * End Else print space End Print
End Loop For int m = 0 and m < n - 2 and m++ Loop For int j = 0 and j < len and j++ if (j == 0 || j == len - 1) Print * End Else print space End End Print
End declare and set int res = n - 1 Loop For int h = res and h >= 0 and h-- declare and set int temp2 = h + n Loop For int k = 0 and k < temp2 and k++ if ((k == n + h - 1) || (k == n - h - 1)) print * End Else print space End End Print
End End Step 2-> In main() Declare variable int n = 5 call pattern(n) STOP
示例
#include <stdio.h> //program to print hexagon pattern void pattern(int n) { int len = 2 * n - 1; //for loop for upper part of a pattern for (int i = 0; i < n; i++) { int temp = i + n; for (int k = 0; k < temp; k++) { if ((k == n + i - 1) || (k == n - i - 1)) printf("*"); else printf(" "); } printf("
"); } //for loop for mid part of a pattern for (int m = 0; m < n - 2; m++) { for (int j = 0; j < len; j++) { if (j == 0 || j == len - 1) printf("*"); else printf(" "); } printf("
"); } //for loop for lower part of a pattern int res = n - 1; for (int h = res; h >= 0; h--) { int temp2 = h + n; for (int k = 0; k < temp2; k++) { if ((k == n + h - 1) || (k == n - h - 1)) printf("*"); else printf(" "); } printf("
"); } } int main() { int n = 5; pattern(n); return 0; }
输出
广告