以 n=5 為例,輸出對稱菱形:
*
***
*****
*******
*********
*******
*****
***
*

菱形可分為上半部(含中線)與下半部:
n-i,星號 2*i-1。i,星號 2*(n-i)-1。
#include
using namespace std;
int main() {
int n = 5; // 可改為 cin >> n 實現動態輸入
// 上半部(含中線)
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n - i; ++j) cout << ' ';
for (int k = 1; k <= 2 * i - 1; ++k) cout << '*';
cout << '\n';
}
// 下半部
for (int i = 1; i <= n - 1; ++i) {
for (int j = 1; j <= i; ++j) cout << ' ';
for (int k = 1; k <= 2 * (n - i) - 1; ++k) cout << '*';
cout << '\n';
}
return 0;
}
// 上半部
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n - i; ++j) cout << ' ';
for (int k = 1; k <= 2 * i - 1; ++k)
cout << (k == 1 || k == 2 * i - 1 ? '*' : ' ');
cout << '\n';
}
// 下半部類似,只在首尾印星號
void printDiamond(int n, char fill = '*', char space = ' ') {
auto line = [&](int spaces, int stars) {
cout << string(spaces, space) << string(stars, fill) << '\n';
};
for (int i = 1; i <= n; ++i) line(n - i, 2 * i - 1);
for (int i = 1; i < n; ++i) line(i, 2 * (n - i) - 1);
}
void diamondRec(int n, int i = 1) {
if (i > 2 * n - 1) return;
int stars = (i <= n) ? 2 * i - 1 : 2 * (2 * n - i) - 1;
int spaces = (i <= n) ? n - i : i - n;
cout << string(spaces, ' ') << string(stars, '*') << '\n';
diamondRec(n, i + 1);
}
n 行,下半部 n-1 行,避免中線重複。std::string 建構子、遞迴、單迴圈數學映射(abs)均可實現,面試時展示多種思路加分。