蔡銘軒 @ Sprout 2021 C/C++語法班
#
##
###
####
#####
######
#######
########
3
#
##
###
5
#
##
###
####
#####
int n;
std::cin >> n;
if (n == 3) {
std::cout << " *" << std::endl
<< " **" << std::endl
<< "***" << std::endl;
} else if (n == 5) {
std::cout << " *" << std::endl
<< " **" << std::endl
<< " ***" << std::endl
<< " ****" << std::endl
<< "*****" << std::endl;
}
怎麼處理?
6
#
##
###
####
#####
######
while (/* condition */) {
/* body */
}
當 (/* 條件為真 */) {
/* 執行程式 */
}
範例:印出 1 到 10
int i = 1;
while (i <= 10) {
std::cout << i << std::endl;
i++;
}
範例:算出 1~100 的偶數和
int i = 2;
int sum = 0;
while (i <= 100) {
sum += i;
i += 2;
}
std::cout << sum << std::endl;
注意事項:終止條件
int i = 1;
while (i <= 100) {
std::cout << i << std::endl;
}
int i = 1;
while (i > 0) {
std::cout << i << std::endl;
i++;
}
無窮迴圈
while (true) {
/* run forever */
}
while (1) {
/* run forever */
}
break: 常見寫法
while (/* condition */) {
/* body */
if (/* another condition */)
break;
}
使用 break 離開當前的迴圈
break: 範例
int answer = 127;
int guess;
while (true) {
std::cout << "Enter a number" << std::endl;
std::cin >> guess;
if (guess == answer) {
std::cout << "You've got it!" << std::endl;
break;
} else {
std::cout << "Wrong..." << std::endl;
}
}
continue: 常見寫法
while (/* condition */) {
/* body 1 */
if (/* another condition */)
continue;
/* body 2 */
}
使用 continue 跳過 body 2,直接進入下一次迴圈
continue: 範例
int a = 0;
int b = 0;
while (true) {
std::cin >> a >> b;
if (b == 0)
continue;
std::cout << "a / b = " << a / b << std::endl;
}
do {
/* body */
}
while (/* condition */);
先執行 body,再判斷條件
do-while: 範例
int answer = 127;
int number = 0;
do {
std::cout << "Enter a number" << std::endl;
std::cin >> number;
}
while (number != answer);
std::cout << "number is 127" << std::endl;
範例:99乘法表
int i = 1;
while (i < 10) {
int j = 1;
while (j < 10) {
std::cout << i << " * " << j << " = " << i * j << " ";
j++;
}
std::cout << std::endl;
i++;
}
3
#
##
###
觀察:當輸入為 時,總共會有 層
聯想到用迴圈執行 次
int n;
std::cin >> n;
int i = 1;
while (i <= n) {
/* 印出第i層 */
i++;
}
第一個步驟:用一個執行 次的迴圈來印出每一層
下一個步驟:在每一次的迴圈內,印出那一層
#
##
###
觀察:在第 層,有 個#,以及 個空白在前面
用一個 次的迴圈印出空白
接著用 次的迴圈印出#
int j = 0;
while (j < n - i) {
std::cout << " ";
j++;
}
j = 0;
while (j < i) {
std::cout << "#";
j++;
}
std::cout << std::endl;
第二個步驟:利用迴圈印出第 層
下一個步驟:將前後兩個部分連接
int n;
std::cin >> n;
int i = 1;
while (i <= n) {
int j = 0;
while (j < n - i) {
std::cout << " ";
j++;
}
j = 0;
while (j < i) {
std::cout << "#";
j++;
}
std::cout << std::endl;
i++;
}
int n = 10;
while (n--) {
std::cout << n << std::endl;
}
int n = 10;
while (--n) {
std::cout << n << std::endl;
}