CPS120 Quiz Notes 4/8/2002
Decision Making in Programs
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.
Relational operators.
Relational operators provide the tools with which programs make decisions with true and false evaluations.
Relational operators:
== equal to
> greater than
< less than
>= greater than or equal to
<= less than or equal to
!= not equal to
Logical operators.
When complex decisions must be coded into an algorithm, it may be necessary to "chain together" a few relational expressions (that use relational operators). This is done with logical operators (also called Boolean operators.)
Logical operators:
& is the logical AND operator
|| is the logical OR operator
Logical operators may be mixed within evaluation statements but you must abide by their 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.
Note that the ! symbol (the logical NOT operator) changes a TRUE to a FALSE.
The complete order of operations including all of the arithmetic, relational, and logical operators including all of the basic arithmetic, relational, & logical operators is:
*, /, %
+, -
<, >, <=, >=, ==, !=
!
||
The if structure.
Practically all computer languages have some sort of if structure. In C++, the if structure is a one-way selection structure:
if (number == 3)
{
cout < "The value of number is 3";
}
All if structures use a control 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.
if (0 < number & number < 10)
{
cout < number < " is greater than 0 but less than 10." < endl;
}
the if/else statement.
The if/else statement adds flexibility to the if decision structure. It is a two-way selection structure since either the block of code after the "if" part will be executed or the block of code after the "else" part will be executed.
The "if" part is executed if the control expression is TRUE while the "else" part is executed if the "if" part is false, guaranteeing one part of the expression to be executed or the other.
if ( number < 0)
{
cout < "The number is negative.";
}
else
{
cout < "The number is zero or positive.";
}
Nested if statements.
If structures 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.
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;
}
}
Switch structure.
The switch structure is a multiple-selection structure that allows you to model even more complicated decision statements than a two-way if/else structure allows. It chooses one of the "cases" depending on the result of the control expression.
Only variables with the INT or CHAR data types may be used in the control expressions (i.e. parentheses) of switch statements. Single quotes must be used around char variables.
Example where the variable menuChoice is an int variable. Note that single quotes are NOT used around the integer values in each case.
switch (menuChoice)
{
case 1:
cout < "You entered menu choice #1";
break;
case 2:
cout < "You entered menu choice #2";
break;
case 3:
cout < "You entered menu choice #3";
break;
default:
cout < "You failed to enter a valid menu choice";
break;
}
The default case, if present, will result if neither of the prior cases apply.
The break statement must be used within each case if you do not want following cases to evaluate once one case is found. When the break statement is executed within a switch, C++ will execute the next statement outside of the switch statement
Loops
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 determinant or definite loop because the programmer knows exactly how many times it will iterate. You can mathematically determine the number of iterations by desk checking 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.
for (num = 1; num <= 3; num++ ) // the counter variable num is initialized to the value 1
{ // the loop will iterate while num is less than or equal to 3
cout < num; // the counter variable num increments by 1 on each iteration
cout < endl;
} // both statements are executed in the body of the loop on each iteration
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.
while (num > 100 ) // the control expression is TRUE if the variable num is greater than 100
{
cout < num;
num = num / 2; // the variable num is reassigned a new value during each iteration
}
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.
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.
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.
do
{
cout <"Enter a number (Enter 0 to quit): ";
cin > num;
if (num == 0)
{ break; }
squared = num* num;
cout < num < " squared is " < squared < '\n';
}
while (1);
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.
for (i = 1; i <= 10; i++ )
{
if (I == 5)
continue;
cout < i < '\n';
}
nested loops.
A loop of any kind may be placed in another loop (of any kind). One must be sure though to entirely encapsulate the inner loop inside of the outer loop, otherwise an error is sure to occur. Two loops are considered to be nested loops if one is enclosed within the other.
for (row = 1; row <= 2; row++ )
{
cout < "row is " < row < endl;
for (column = 1; column <= 3; column++ )
{
cout < "column is " < column < endl;
}
}
Notice the blank line above the inner for loop and below the inner for loop. Blank lines should be used there for good style and readability.
Functions
"scope of variables."
Variables are either global or local in nature. Global variables are ones that are declared outside and above the main function. They can be used in any function throughout the program. It is not wise to use global variables any more than you have to. One small error (for example, miscalculating a value) could lead to multiple, hard-to-find errors in large programs. Local variables are ones that are declared inside of a function, including main. They cannot be used or referred to in other functions.
In order to strengthen your program and functions' autonomy and encapsulation, you should avoid the use of global variables and try to use local variables instead.
The scope of a variable is the area in which it can be legally referenced. A global variable's scope is the whole program. A local variable's scope is the function in which it is declared.
In the example program above (with the function printMyName), the variable userInput is a local variable which belongs to the main function. The variable i is a local variable to the function printMyName. (numOfTimes isn't really a variable. It is a parameter technically. See objective 3 for more details on parameters.)
functions in a C++ program.
A function must be given a valid identifier as a name. A good name for a function that computes sales tax would be computeSalesTax.
The first line of a function is called the function header. Before the name of the function you must specify a "return type." The return type is the data type of the value that is returned by the function to the calling function.
After the name of the function in the function header, you must include a parameter list. The parameter list is a pair of parentheses with 0 or more parameters listed. Each parameter is passed to the function from the calling function. Immediately preceding each parameter, you must identify the data type of that parameter. If the function does not return any value, you must type the word void as the return type. An example of a function header is:
double computeTax(double myPrice, double myTaxRate)
where the name of the function is computeTax, the return type is double, and the passed parameters are myPrice and myTaxRate.
Following the function header comes the body of the function which is enclosed in a pair of curly braces. If the function is not a void function, there must be a return statement at the end of the function. The return statement returns a computed value to the calling function.
double computeTax(double myPrice, double myTaxRate)
{
double result = 0.0;
result = myPrice * myTaxRate;
return result;
}// end of computeTax
how data is passed to functions.
Data is passed to functions as arguments (sometimes referred to as actual parameters). When a function is "called" by the main function (or another function), one or more arguments are passed to the function. On the receiving end, the function accepts these arguments (technically, as formal parameters). The variable names of the arguments (that is, actual parameters) from the "calling" function do not have to be the same as the names of the formal parameters in the "called" function. But, the datatypes of the arguments and the parameters should match exactly. An error could occur if the data types do not match.