Control statements

Reading: Chapter 6

There are basically two types of control statements:

Conditional statements

A conditional statement looks like

if(<condition>) {
    <toDoIfTrue>
}
For example:
#include <iostream>
#include <string>

using namespace std;

int main() {
    cout << "Type a number. ";
    double x;
    cin >> x;
    if(x < 0) {
        x = -x;
    }
    cout << "Absolute value is " << x << endl;
    return 0;
}

You'll see we're using a comparison operators here. These are the C++ comparison operators:

<less than
<=at most
>greater than
>=at least
==equal
!=not equal

We can build up more complicated conditional statements using the else clause.

#include <iostream>
#include <string>

using namespace std;

int main() {
    char order;
    cout << "Type a number. ";
    cin >> order;
    double price = 0.00;
    if(order == 's') { //sandwich
        cout << "Would you like fries with that?" << endl;
        price = 4.20;
    } else if(order == 'f') { // fries
        cout << "Is that all?" << endl;
        price = 2.10;
    } else if(order == 'd') { // drink
        cout << "Soda or pop?" << endl;
        price = 0.80;
    } else {
        cout << "That's gibberish!" << endl;
    }
    cout << "That will be $" << price << "." << endl;
    return 0;
}

Iteration statements

We'll see two types of iteration statements in this course. The first is the while loop.

while(<condition>) {
    <toDoWhileTrue>
}
Now we can implement PRIME-TEST-ALL from the first day:
#include <iostream>
#include <string>

using namespace std;

int main() {
    int totest;
    cout << "Whose primality should I test? ";
    cin >> totest;

    int trial = 2;
    while(trial * trial <= totest) {
        if(totest % trial == 0) {
            cout << totest << " is not prime" << endl;
            return 0;
        }
        trial = trial + 1;
    }
    cout << totest << " is prime" << endl;
    return 0;
}