Objective #1: Understand how true and false is represented in
C++.
- When decisions are made in a computer program, they are simply the
result of a computation in which the final result is either true or
false. Computer programs do not have intuition or "gut feelings";
they simply make thousands of yes-or-no-like decisions at blinding speeds.
The computer programmer must set up these decisions within the algorithm
of a computer program to achieve the desired results.
- The value zero (0) is considered to be false by C++. Any positive
or negative value is considered to be true. Many people
assume that only positive one is considered to be true but technically
C++ evaluates any non-zero value to be true.
- Boolean expressions are used in certain kinds of C++ statements.
A Boolean expression evaluates to either true or false. A simple example
of a Boolean expression is (price < 10.00)
where price is a variable. If
price is equal to the value 8.34, then
the Boolean expression as a whole would be considered to be true since
8.34 is indeed less than 10.00.
Objective #2: Use relational operators.
- Relational operators provide the tools with which programs
make decisions with true and false evaluations.
Relational operators:
== equal to
NOTE: this is two equals symbols next to each
other, not to be confused with the assignment operator, =
> greater than
< less than
>= greater than or equal to
<= less than or equal to
!= not equal to
Objective #3: Use logical operators.
- Use this truth table to determine the results of the logical
operators. In this table, 1 represents true and 0 represents false.
| AND |
|
OR |
|
NOT |
| A |
B |
A && B |
|
A |
B |
A || B |
|
A |
!A |
| 0 |
0 |
0 |
|
0 |
0 |
0 |
|
0 |
1 |
| 0 |
1 |
0 |
|
0 |
1 |
1 |
|
1 |
0 |
| 1 |
0 |
0 |
|
1 |
0 |
1 |
| 1 |
1 |
1 |
|
1 |
1 |
1 |
- Logical operators may be mixed within evaluation statements but you
must abide by their precedence rules (aka order of operations):
NOT operator (!), AND operator (&&), OR operator (||)
You must remember that the && operation is always performed
before the || operation because && is similar to multiplication
in normal arithmetic while || is similar to addition.
- Short-circuit evaluation in C++ allows the compiler to quickly
evaluate a logical expression in some cases without having to completely
evaluate each part of the expression.
Objective #4: Be able to use the if statement.
- Practically all computer languages have some sort of if structure.
In C++, the if structure (can be called an "if statement" as well) is a one-way selection structure.
Example:
if (number ==
3)
{
cout << "The
value of number is 3";
}
- All if structures use a control expression (or sometimes called
controlling expression) to determine if the code in the braces
is to be executed. In the example above,
(number == 3) is the control expression.
Note the use of the "double equals" relational operator ==
and not the assignment operator =.
- Be sure to place the semicolon at the end of each statement within
the braces, which can contain many executable statements.
- Realize that you must use the AND operator (&&) to form a
compound relational expression. The the following syntax is invalid:
if (0 < number < 10)
{
cout << number << "
is greater than 0 but less than 10." << endl;
}
Rather the following syntax must be used:
if (0 < number && number <
10)
{
cout << number << "
is greater than 0 but less than 10." << endl;
}
- According to our Coding Standards,
you must use curly braces around the body of an if
statement even if there is only one statement. If you use the following
statement in a program assignment for this class, you will lose points
for not including curly braces even though the statement would not cause
compile errors.
if (num > 10)
cout << num << " is greater than
10";
This is stressed so that beginner programmers develop safe habits and
good style. In the following code segment
if (num > 0)
cout << "num is positive" <<
endl;
cout << "num is not zero"
<< endl;
the body of the if statement is only considered to be the first cout
statement according to the C++ compiler. The second statement would
execute even if num is equal to zero.
The indentation of the second statement has no effect on the way the
compiler interprets this code.
- According to our Coding Standards,
you must not write one line if statements. If you use the following
statement in a program assignment for this class, you will lose points
for not breaking it up over multiple lines even though it would not
cause compile errors.
if (num > 10) cout << num <<
" is greater than 10";
- Avoid the following common mistakes that are made with if
statements:
Always use the "double equals" symbol (i.e. comparison
operator) rather than the assignment operator in control expressions:
int num = 0:
if (num == 5)
{
cout << "hello world" << endl;
}
which would not display "hello world"
rather than:
int num = 0;
if (num = 5)
{
cout << "hello world" << endl;
}
which would assign the value 5 to the variable num and then display
"hello world"
Avoid using an unnecessary semicolon after a control expression:
if (num > 0);
{
cout << "num is positive" <<
endl;
}
which would cause the phrase "num is positive" to be displayed
even if num is negative.
- An interesting use of the mod operator ( % ) is to determine whether a variable is even or odd. Since any even number leaves a remainder of 0 when divided by two and any odd number leaves a remainder of 1 when divided by two, we can use the following if statement
if (num % 2 == 0)
{
cout << num << " is an even number" << endl;
}
else if (num % 2 == 1)
{
cout << num << " is an odd number" << endl;
}
- We will not be studying the enumeration type in this CMPSC 101 course
as explained on p. 64.
- We will not be studying the conditional operator (e.g. (n1 > n2)
? n1 : n2 ) in this CMPSC 101 course as explained on pp. 64 & 65.
Objective #6: Be able to use the if/else statement.
Objective #7: Be able to use and interpret nested if statements.
- if statements and if
else statements can be nested within one another in order
to model complex decision structures. Be sure to use the braces and
semicolons properly when coding such structures. Also, be sure to rigorously
check the logic of your algorithm since it is quite easy to overlook
possible errors.
- Example:
The if statement that tests for divisibility
by 5 is located inside of the if statement
that tests for divisibility by 3 therefore it is considered to be a
nested if statement.
if (number % 3 == 0)
{
cout
<< number << " is divisible by 3." << endl;
if
(number % 5 == 0)
{
cout << number << " is divisible by 3 and 5."
<< endl;
}
}
Notice the blank lines around the inner if
statement for good style.
Objective #8: Be able to use the switch statement. (This topic may not be covered this semester. Ask the instructor if you are responsible for studying switch statements.)
Objective #9: Be able to explain the importance of loops in programs.
- In order to write a non-trivial computer program, you almost always
need to use one or more loops. Loops allow your program to repeat groups
of statements a specified number of times. Loops are an example of an
iteration structure.
- It is important to be aware of how many iterations
a given loop is expected to perform. If a loop does not iterate a finite
number of times, it is considered to be an infinite loop. Rarely would
a programmer ever intentionally incorporate an infinite loop into a
program, however it is easy to do so by mistake.
Objective #10: Be able to use for loops.
- A for
loop always executes a specific number of iterations. Use a for
loop when you know exactly how many times a set of statements must be
repeated.
- A for loop is called a determinate
or definite loop because the programmer knows exactly how many
times it will iterate. You can mathematically determine the number of
iterations by deskchecking the logic of the loop.
- After the keyword for a set of parentheses
is necessary with three expressions as parameters.
for (initializing expression; control expression; step expression)
{
// one or more statements
}
- The initializing
expression sets the counter variable for the
loop to its initial value.
- The control expression
ends the loop at the specified moment.
- The step expression
changes the counter variable,effectively determining
the number of iterations. The counter variable often increments by one,
but it may increment, decrement, or count in other ways.
- Notice that semicolons are used to separate the three expressions
above, not commas.
- Example:
for (num = 1; num <= 3; num++ ) //
num is initialized to the value 1
{
// loop iterates while num is less than or equal
to 3
cout << num;
// num increments by 1 on each iteration
cout << endl;
}
// both statements execute
on each iteration
- It is possible to have variable increase by a value other than one.
For example the following loop would iterate 4 times with the variable
num taking on the values 1, 4, 7, and 10. The step expression adds 3
to the value of num on each iteration.
for (num = 1; num <= 10;
num = num + 3)
It is a common error though for students to use
for (num = 1; num <= 9 ; num + 3)
which causes a compile error.
- It is possible to initialize the loop variable within the initializing
expression. But I recommend against CMPSC 101 students initializing
loop variables within the loop and may deduct points for doing so. Students
are required to declare loop variables at the top of the function (e.g.
main function) where they are used.
for (int num
= 1; num <= 9; num = num + 3)
{
cout
<< num << endl;
}
- If a loop only contains one body statement, the compiler doesn't require
the use of curly braces. But I recommend against doing so for CMPSC
101 students. According to our Coding
Standards for this course, you must use curly braces with for, while,
and do/while loops.
That is, do not use the following
syntax without curly braces:
for (num = 0; num < 10; num++)
cout << num << endl;
- According to our Coding Standards,
you must blank lines above and below any loop so that it stands out
and is easier to read by fellow programmers.
- We will not be studying the comma operator in this CMPSC 101 course.
(The textbook explains how the comma operator can be used on p. 72.)
Objective #11: Be able to use while loops.
- A while
loop does not necessarily iterate a specified number of times. Rather,
as long as its control expression
is true, a while loop will continue
to iterate. This type of loop is very useful in situations where a for
loop would be ineffective, particularly when the user is given the opportunity
to interact with the program.
- A while loop is considered to be
an indeterminate or indefinite loop because usually only
at run-time can it be determined how many times it will iterate.
- A while loop is also considered to
be a top-checking loop, since the control expression is located
on the first line of code with the while keyword. That is, if the control
expression initially evaluates to false, the loop will not iterate even
once.
- After the keyword, while, a control expression is necessary.
while (control expression)
{
//
one or more statements
}
The control expression must evaluate to true in order for the while
loop to iterate even once.
- Example:
while (num > 100 )
// control expression is true if num is greater than 100
{
cout << num;
num = num / 2;
// num is reassigned a new value during each iteration
}
Objective #12: Be able to use do while loops.
- As with a while loop, a do
while loop does not necessarily iterate
a specified number of times. However, it is guaranteed that a do while
loop will iterate at least one time because its control expression is
placed at the end of the loop. This loop is useful when you want to
guarantee at least one iteration of the loop.
- Like a while loop, a do while loop is considered to be an indeterminate
or indefinite loop.
- A do while loop is considered to
be a bottom-checking loop, since the control expression is located
after the body of the loop after the while
keyword. A do while loop is guaranteed
to iterate at least once even if the control expression evaluates to
false.
- The do keyword is placed on
a line of code by itself at the top of the loop. A block of statements
follows it with a control expression after the keyword while
at the bottom of the loop.
do
{
//
body statements would be placed here
}while (control expression);
The control expression must evaluate to true in order for the do
while loop to iterate after the first time.
- Example:
do
{
cout << "Enter a number (0 to quit):
";
cin >> num;
sum = sum + num;
cout << "Current sum is " <<
sum << '\n';
} while (num != 0 );
- Don't forget to include the required semicolon after the control expression.
Objective #13: Be able to use the break and continue statements.
- A break
statement is used to stop the execution of a loop immediately and to
continue by executing the statement that comes directly after the loop.
Only use the break statement when it is not practical to control the
execution of a loop with its control expression. That is, only use a
break statement when absolutely necessary.
- A continue
statement is used to stop the execution of the statements in the loop's
body on that particular iteration and to continue by starting the next
iteration of the loop.
Objective #14: Be able to use and interpret nested loops.
Notice the blank
lines around the inner loop for good style.