以下是用C語言打印菱形的代碼示例:
#include <stdio.h>
int main() {
int n, c, k, space = 1;
printf("Enter number of rows: ");
scanf("%d", &n);
space = n - 1;
for (k = 1; k <= n; k++) {
for (c = 1; c <= space; c++) {
printf(" ");
}
space--;
for (c = 1; c <= 2*k-1; c++) {
printf("*");
}
printf("\n");
}
space = 1;
for (k = 1; k <= n - 1; k++) {
for (c = 1; c <= space; c++) {
printf(" ");
}
space++;
for (c = 1; c <= 2*(n-k)-1; c++) {
printf("*");
}
printf("\n");
}
return 0;
}
在上面的代碼中,用戶輸入行數,然后利用循環打印出菱形。這個程序首先打印上半部分的菱形,然后再打印下半部分的菱形。