代碼使用 using System;、namespace、Console.WriteLine、string[] args —— 明確為 C# 代碼。
// 原 for 循環
for (int x = 0; x < 9; x++) {
if (x == 0 || x == 8) {
for (int i = 0; i < 9; i++) Console.Write("*");
Console.WriteLine();
} else {
for (int i = 0; i < 9; i++) {
if (i == 0 || i == 8) Console.Write("*");
else Console.Write(" ");
}
Console.WriteLine();
}
}
// 等價 while 版本
int x = 0;
while (x < 9) {
if (x == 0 || x == 8) {
int i = 0;
while (i < 9) { Console.Write("*"); i++; }
Console.WriteLine();
} else {
int i = 0;
while (i < 9) {
if (i == 0 || i == 8) Console.Write("*");
else Console.Write(" ");
i++;
}
Console.WriteLine();
}
x++;
}
Console.ReadLine();
for (init; condition; increment) {
body;
}
// 等價於
init;
while (condition) {
body;
increment;
}
#include
int main() {
int x = 0;
while (x < 9) {
if (x == 0 || x == 8) {
int i = 0;
while (i < 9) { printf("*"); i++; }
printf("\n");
} else {
int i = 0;
while (i < 9) {
if (i == 0 || i == 8) printf("*");
else printf(" ");
i++;
}
printf("\n");
}
x++;
}
getchar(); // 暫停
return 0;
}
********* * * * * * * * * * * * * * * *********
9×9 空心正方形 (非長方形)。