c 程式流程結構,選擇結構,迴圈結構,跳轉語句

2021-10-06 22:59:13 字數 3428 閱讀 9173

c/c++支援最基本的三種程式執行結構:順序結構、選擇結構、迴圈結構

作用:執行滿足條件的語句

if語句的三種形式

1.單行格式if語句:if(條件)

例項:

#include using namespace std;

int main()

system("pause");

return 0;

}

注意:if條件表示式後不要加分號

2.多行格式if語句:if(條件)else;

例項:

#include using namespace std;

int main()

else

system("pause");

return 0;

}

3.多條件的if語句:if(條件1)else if(條件2) ... else

例項:

#include using namespace std;

int main()

else if (score > 500)

else if(score > 400)

else

system("pause");

return 0;

}

巢狀if語句:在if語句中,可以巢狀使用if語句,達到更精確的條件判斷

例項:

#include using namespace std;

int main()

else if (score > 650)

else

}else if (score > 500)

else if(score > 400)

else

system("pause");

return 0;

}

作用:通過三目運算子實現簡單地判斷

語法表示式1 ? 表示式2 : 表示式3

解釋

如果表示式1的值為真,執行表示式2,並返回表示式2的結果

如果表示式1的值為假,執行表示式3,並返回表示式3的結果

例項:

#include using namespace std;

int main()

注意:c++中三目運算子返回值的是變數,可以繼續賦值

**作用:**執行多條件分支語句

語法:

switch(表示式)

例項:

#include using namespace std;

int main()

system("pause");

return 0;

}

注意1:switch語句中表示式型別只能是整型或者字元型

注意2:case梨如果沒有break,那麼程式會一直向下執行

注意3:與if語句比,對於多條件判斷時,switch的結構清晰,執行效率高,缺點是switch不可以判斷區間

**作用:**滿足迴圈條件,執行迴圈語句

語法:whlie(迴圈條件)

解釋:只要迴圈跳進的結果為真,就執行迴圈語句

例項:

#include using namespace std;

int main()

system("pause");

return 0;

}

注意:在執行迴圈語句時候,程式必須提供調出迴圈的介面,否則出現死迴圈

作用:do while(迴圈條件);

**注意:**與while的區別在於do…while會先執行一次迴圈,再判斷迴圈條件

例項:

#include using namespace std;

int main() while (num < 10);

//do...while和while迴圈區別在於,do...while會執行一次迴圈語句

system("pause");

return 0;

}

注意:do…while和while迴圈區別在於,do…while會執行一次迴圈語句

**作用:**滿足迴圈條件,執行迴圈語句

語法:for(起始表示式;條件表示式;末尾迴圈體)

例項:

int main()

cout << endl;

}

例項2:列印九九乘法表

#include using namespace std;

int main()

cout << endl;

}cout << endl;

return 0;

}

**作用:**用於跳出選擇結構或者迴圈結構

break使用的時機:

例項1:

int main()

}

例項2:

int main()

cout << i << endl;

}}

例項3:

int main()

cout << "*";

}cout << endl;

}}

例項:

int main()

cout << i 《注意:continue並沒有使整個迴圈終止,而break會跳出迴圈

**作用:**可以無條件跳轉語句

語法:goto標記;

**解釋:**如果標記的名稱存在,執行到goto語句時,會跳轉到標記的位置

例項:int main()

流程結構(選擇結構,迴圈結構)

if單選擇結構if 判斷條件 if雙選擇結構if 判斷條件 elseif多選擇結構if 判斷條件1 else if 判斷條件2 else if 判斷條件3 else巢狀的if結構 while 布林表示式 列印1 100的和 public class whiledemo03 system.out.pr...

c 程式流程結構 迴圈結構

2 do while迴圈語句 3 for迴圈語句 4 巢狀迴圈 語法 while 迴圈條件 解釋 只要迴圈條件的結果為真,就執行迴圈語句。例子 列印0 9 int main system pause return0 注意1 一定要避免死迴圈。描述 隨機生成乙個1 100之間的數字,玩家進行猜測,如果...

C 程式流程結構 選擇結構

格式 if 條件 注意1 條件後面不能加分號 語法 if 條件 else 語法 if 條件1 else if 條件2 else include include using namespace std intmain elseif 700 score 650 else elseif 600 score...