Control Structures

Selective Statements

The if-else Statement

  if (score > 60)
    cout << "及格";

  if (score > 60)
    cout << "及格";
  else
    cout << "不及格";

Nested if-else Statement

  if (score > 80)
    cout << "甲";
  else
    if (score > 70)
      cout << "乙";
    else
      if (score > 60)
        cout << "丙";
      else ...
注意: else's 和最接近的 if 配對

conditional operator ?:

  cout << (score >= 60 ? "及格" : "不及格") << endl;

Switch Statement

switch(grade)
{
    case 'A' :
    case 'B' : cout << "Good work";
	           break;
    case 'C' : cout << "Average work";
	           break;
    case 'D' :
    case 'F' : cout << "Poor work";
	           break;
    default  : cout << grade << " is not a legal letter grade.";
               break;
}
注意: exit, break, continue 不同處:
    exit      terminates program execution
    break     exits from the innermost block
    continue  terminates the current loop iteration

Example: num2eng.cc

Looping Statements

The while Structure

Loop Design Examples

Essentials of Counter-controlled Loop

The for Structure

  for (<<declare loop var>>; <<while test>>; <<increment loop var>>)
    <<statement>>

約略相當於
  <<declare loop var>>
  while (<<while test>>)
    {
      <<statement>>
      <<increment loop var>>
    }

例子: counting

#include <iostream.h>

int main()
{
  int product;

  for (int i = 1; i <= 10; i++)
    cout << i << endl;

  return 0;
}

The do/while statement

#include <iostream.h>

int main()
{
  int i=1;

  do {
      cout << i << " ";
  } while (++i <= 10);

  return 0;
}
注意: 此迴圈至少執行一次

While/Do-while Usage

while loop

cout << "Enter your age: ";
cin >> age;
while (age <=0)
{
    cout << "Your age must be positive." << endl;
    cout << "Enter your age: ";
    cin >> age;
}

do-while loop

do
{
    cout << "Enter your age: ";
    cin >> age;
    if (age <= 0)
        cout << "Your age must be positive." << endl;
} while (age <=0);

Testing and Debugging

Example

#include <iostream.h>
#include <iomanip.h>

int main()
{
    int sum=0, n=1;     // precondition

    while(n<=10)        // loop invariant:
    {                   //     1 <= n <= 11
        sum += n;       //     sum = 0+1+2+...+(n-1)
        n++;            //     iterations = n-1
    }

    cout << "Sum = " << setw(6) << sum << endl;
    cout << " n  = " << setw(6) << n   << endl;

                        // postconditon:
                        //   sum = 0+1+2+...+10
                        //   n = 11
}