Sequential Execution
C++ programs execute sequentially, line by line, top to bottom
Every time you run one (with what we know now), it will do exactly the same thing (except for any differences in the data).
What if we want it to do different things depending on the input?
Example: What happens if you try to set num_pages to -1 in the
card catalog entry?
The function should print an error message
What we need is the ability to execute different pieces of code
depending on the situation, rather than blindly executing every line.
Selective Execution
The "if" statement allows us to execute a piece of code or not, based on the value of the expression we pass to it
Pseudocode:
Example:
int age;
cout << "Please enter your age: ";
cin >> age;
if(age <= 0) {
cout << "Age must
be > 0\n";
exit(-1);
}
cout << "Your age is " << age << "\n";
The "if" statement also allows us to choose between two alternatives
Pseudocode:
Example: Bar doorman function
int age;
cout << "Please enter your age: ";
cin >> age;
if(age <= 0) {
cout << "Age must
be > 0\n";
exit(-1);
}
if(age >= 21) {
cout << "Welcome\n";
} else {
cout << "I'm sorry,
you can't drink here\n";
}
Example:
if(num_credits < 0) {
cout << "Come on,
get real\n";
} else if (num_credits < 12) {
cout << "Part-time
student\n";
} else if (num_credits < 18) {
cout << "Full-time
student\n";
} else {
cout << "Glutton for
punishment\n";
}
Conditions
Logical expressions that evaluate to either TRUE or FALSE.
Logical expressions are also called boolean expressions after George
Boole.
Simple Boolean Expressions
< (is less than)
> (is greater than)
== (is equal to)
!= (is not equal to)
<= (is less than or equal to)
>= (is greater than or equal to)
Examples:
Note: These operators don't work for strings.
Compound Boolean Expressions
Boolean expressions don't string together like numerical expressions.
Examples:
Switch Statements
A cleaner way to select among multiple alternatives.
Given a numeric value x, where we want to execute different blocks of code based on the value of x, we can write:
switch(x) {
case 0:
cout << "Invalid value for x";
break;
case 1:
y = z;
break;
case 2:
y = 1/z;
break;
default:
y = 37;
break;
}