C++ Control Structures
Earlier in the course, we saw that any computable algorithm can be accomplished by using a collection of three different control structures: sequence, selection, and looping. In C++, the sequence control is the default: i.e., the "regular" behavior of a program is to execute each statement one after the other in sequence, unless one of the other two control structures, selection or looping, is present. So there is not much to say about sequence, it's just what you expect to happen.
Selection in C++: The most common selection statement in C++ (there are others which you will learn about later in this course) is the if .. else statement. The if .. else statement has two parts: the if part and the else part. In the if .. else statement below, you should notice that there is a expression in parentheses following the keyword if. This expression is called the "boolean expression." When the if .. else statement runs, it checks the boolean expression, and if the expression is true, then the if part is executed. If the boolean expression is false, then the else part is executed. In the example statement below, the boolean expression is false (i.e., myName does not contain the same value as yourName), so the else part is executed and the string "The names are not the same" is printed.
Please note, the boolean expression does not have to be an equality--any expression that has a true or false result is allowable.
string myName = "Joe";
string yourName = "Jim";
if (myName == yourName) {
// if the names are the same then do this part
cout << "The names are the same\n";
} else {
// if the names are not the same do this part
cout << "The names are not the same\n";
}
Looping (or Iteration) in C++: There are two common looping (or iteration) statements in C++: the while statement and the for statement . See these lectures notes for the while statement and these for the for statement.