Statements

If Statements

cout << "Enter % score: ";
int score;
cin >> score;
if (score >= 88) {
    cout << "A";
} else if (score >= 76) {
    cout << "B";
} else if (score >= 65) {
    cout << "C";
} else if (score >= 50) {
    cout << "D";
} else if (score > 0) {
    cout << "F";
} else {
    cout << "N"; // N means no grade assigned
}
cout << endl;

While Loops

int i = 10;
while (i > 0) {
    cout << i << " ...\n";
    i--;
}
cout << "Blast off!\n";

For Loops

for(int i = 10; i > 0; --i) {
    cout << i << " ...\n";
}
cout << "Blast off!\n";

prefer for-loops to while-loops

for-loops put the loop control information in one place

Ranged For Loops

string s = "left";
for(char c : s) {      // : read as "in"
    cout << c << '\n';
}
// l
// e
// f
// t

we’ll see more of these later when discussing strings and vectors

Try/Catch

try/catch statements are used to handle errors

try {
    cout << "What's your favourite real number? ";
    double x;
    cin >> x;
    if (x == 0.0) throw runtime_error("division by 0");
    cout << x << " inverted is " << (1 / x) << endl;
} catch (exception e) {
    cout << "Oops, sorry: can't divide by 0\n";
}

in this course we will generally handle errors explicitly with if-statements and error

If-statements and Errors

during development, error is often a better error-handling approach

it makes the error-handling explicit

void handle_if() {
    cout << "What's your favourite real number? ";
    double x;
    cin >> x;
    if (x == 0.0) error("division by 0");
    cout << x << " inverted is " << (1 / x) << endl;
}

Table Of Contents

Previous topic

Variables

Next topic

Strings and Vectors