C++‎ > ‎

控制結構 Control Structures

控制程式的流程和執行步驟,以中括號 { } 控制範圍

條件結構 Conditional structure: if and else

  • 單行
if (x == 100)
  cout << "x is 100";


  • 多行
if (x == 100)
   cout << "x is ";
   cout << x;
}
  • 或者
if (x == 100)
  cout << "x is 100";
else
  cout << "x is not 100";
  • 多種條件
if (x > 0)
  cout << "x is positive";
else if (x < 0)
  cout << "x is negative";
else
  cout << "x is 0";

重覆結構 Iteration structures (loops)

  • while 迴圈
  while (n>0) {
    cout << n << ", ";
    --n;
  }

  • do-while 迴圈
  do {
    cout << "Enter number (0 to end): ";
    cin >> n;
    cout << "You entered: " << n << "\n";
  } while (n != 0);

  • for 迴圈
  for (int n=10; n>0; n--) {
    cout << n << ", ";
  }

跳脫敘述 Jump statements

break 敘述

跳出目前區塊 { ... }
break;

continue 敘述

直接進行下一圈 { ... }
continue;

goto 敘述

直接跳到指定的位置,搭配冒號 xxx: 使用
  int n=10;
  loop:
  cout << n << ", ";
  n--;
  if (n>0) goto loop;
  cout << "FIRE!\n";

exit 函式

被定義在 cstdlib 函式庫內,exit(0); 代表程式正常結束
exit(0);

選擇結構 selective structure: switch.

switch (x) {
  case 1:
    cout << "x is 1";
    break;
  case 2:
    cout << "x is 2";
    break;
  default:
    cout << "value of x unknown";
  }
不使用 break; 的話會進行到下一個 case  




Comments