Sei sulla pagina 1di 8

Review Questions and Exercises

Short Answer
1. Describe the difference between the if/else if statement and a series of if statements.
2. In an if/else if statement, what is the purpose of a trailing else?
3. What is a flag and how does it work?
4. Can an if statement test expressions other than relational expressions? Explain.
5. Briefly describe how the && operator works.
6. Briefly describe how the || operator works.
7. Why are the relational operators called relational?
8. Why do most programmers indent the conditionally executed statements in a decision structure?

Fill-in-the-Blank
9. An expression using the greater-than, less-than, greater-than-or-equal to, less-than-or equal-to, equal, or not-equal to
operator is called a(n) __________ expression. Relational/Boolean expression
10. A relational expression is either __________ or __________. T/F
11. The value of a relational expression is 0 if the expression is __________ or 1 if the expression is __________. F/T
12. The if statement regards an expression with the value 0 as __________. F
13. The if statement regards an expression with a nonzero value as __________. T
14. For an if statement to conditionally execute a group of statements, the statements must be enclosed in a set of
__________. Braces
15. In an if/else statement, the if part executes its statement or block if the expression is __________, and the else part
executes its statement or block if the expression is __________. T/F
16. The trailing else in an if/else if statement has a similar purpose as the __________ section of a switch statement.
Default
17. The if/else if statement is actually a form of the __________ if statement. Nested
18. If the sub-expression on the left of the __________ logical operator is false, the right sub-expression is not checked.
AND/&&
19. If the sub-expression on the left of the __________ logical operator is true, the right sub-expression is not checked.
OR/||
20. The __________ logical operator has higher precedence than the other logical operators. NOT/!
21. The logical operators have __________ associativity. Left-to-Right
22. The __________ logical operator works best when testing a number to determine if it is within a range. AND/&&
23. The __________ logical operator works best when testing a number to determine if it is outside a range. OR/||
24. A variable with __________ scope is only visible when the program is executing in the block containing the variable’s
definition. Local/Block Scope
25. You use the __________ operator to determine whether one string object is greater than another string object.
Relational
26. An expression using the conditional operator is called a(n) __________ expression. Conditional
27. The expression that is tested by a switch statement must have a(n) __________ value. Integer
28. The expression following a case statement must be a(n) __________ __________. Integer literal
29. A program will “fall through” a case section if it is missing the __________ statement. Break
30. What value will be stored in the variable t after each of the following statements executes?
A) t = (12 > 1); __________
B) t = (2 < 0); __________
C) t = (5 == (3 * 2)); __________
D) t = (5 == 5); __________

33. Using the following chart, write an if/else if statement that assigns .10, .15, or .20 to commission , depending on the
value in sales .

Sales Commission Rate


Up to $10,000 10%
$10,000 to $15,000 15%
Over $15,000 20%

34. Write an if statement that sets the variable hours to 10 when the flag variable minimum is set.
35. Write nested if statements that perform the following tests: If amount1 is greater than 10 and amount2 is less than
100, display the greater of the two.
36. Write an if statement that prints the message “The number is valid” if the variable grade is within the range 0
through 100.
37. Write an if statement that prints the message “The number is valid” if the variable temperature is within the range −
50 through 150.

True or False
42. T F The = operator and the == operator perform the same operation when used in a Boolean expression.
43. T F A variable defined in an inner block may not have the same name as a variable defined in the outer block.
44. T F A conditionally executed statement should be indented one level from the if statement.
45. T F All lines in a block should be indented one level.
46. T F It’s safe to assume that all uninitialized variables automatically start with 0 as their value.
47. T F When an if statement is nested in the if part of another statement, the only time the inner if is executed is when
the expression of the outer if is true.
48. T F When an if statement is nested in the else part of another statement, as in an if/else if, the only time the inner if
is executed is when the expression of the outer if is true.
49. T F The scope of a variable is limited to the block in which it is defined.
50. T F You can use the relational operators to compare string objects.
51. T F x != y is the same as (x > y || x < y)
52. T F y < x is the same as x >= y
53. T F x >= y is the same as (x > y && x = y)

Assume the variables x = 5, y = 6, and z = 8. Indicate by circling the T or F whether each of the following conditions is true
or false:

54. T F x == 5 || y > 3
55. T F 7 <= x && z > 4
56. T F 2 != y && z != 4
57. T F x >= 0 || x <= y

1. Minimum/Maximum
Write a program that asks the user to enter two numbers. The program should use the conditional operator to
determine which number is the smaller and which is the larger.

2. Roman Numeral Converter


Write a program that asks the user to enter a number within the range of 1 through 10. Use a switch statement to
display the Roman numeral version of that number.
Input Validation: Do not accept a number less than 1 or greater than 10.
Review Questions and Exercises
Short Answer
1. Why should you indent the statements in the body of a loop?
2. Describe the difference between pretest loops and posttest loops.
3. Why are the statements in the body of a loop called conditionally executed statements?
4. What is the difference between the while loop and the do-while loop?
5. Which loop should you use in situations where you wish the loop to repeat until the test expression is false, and the
loop should not execute if the test expression is false to begin with?
6. Which loop should you use in situations where you wish the loop to repeat until the test expression is false, but the
loop should execute at least one time?
7. Which loop should you use when you know the number of required iterations?
8. Why is it critical that counter variables be properly initialized?
9. Why is it critical that accumulator variables be properly initialized?
10. Why should you be careful not to place a statement in the body of a for loop that changes the value of the loop’s
counter variable?
11. What header file do you need to include in a program that performs file operations?
12. What data type do you use when you want to create a file stream object that can write data to a file?
13. What data type do you use when you want to create a file stream object that can read data from a file?
14. Why should a program close a file when it’s finished using it?

Fill-in-the-Blank
16. To __________ a value means to increase it by one, and to __________ a value means to decrease it by one. Inc/dec
17. When the increment or decrement operator is placed before the operand (or to the operand’s left), the operator is
being used in __________ mode. postfix
18. When the increment or decrement operator is placed after the operand (or to the operand’s right), the operator is
being used in __________ mode. prefix
19. The statement or block that is repeated is known as the __________ of the loop. body
20. Each repetition of a loop is known as a(n) __________. iteration
21. A loop that evaluates its test expression before each repetition is a(n) __________ loop. pretest
22. A loop that evaluates its test expression after each repetition is a(n) __________ loop. posttest
23. A loop that does not have a way of stopping is a(n) __________ loop. infinite
24. A(n) __________ is a variable that “counts” the number of times a loop repeats. counter variable
25. A(n) __________ is a sum of numbers that accumulates with each iteration of a loop. Running total
26. A(n) __________ is a variable that is initialized to some starting value, usually zero, and then has numbers added to
it in each iteration of a loop. Loop control variable
27. A(n) __________ is a special value that marks the end of a series of values. sentinel
28. The __________ loop always iterates at least once. Do-while
29. The __________ and __________ loops will not iterate at all if their test expressions are false to start with.
While/for
30. The __________ loop is ideal for situations that require a counter. For loop
31. Inside the for loop’s parentheses, the first expression is the __________ , the second expression is the __________ ,
and the third expression is the __________. Initialization/test/update
32. A loop that is inside another is called a(n) __________ loop. Nested loop
33. The __________ statement causes a loop to terminate immediately. break
34. The __________ statement causes a loop to skip the remaining statements in the current iteration. continue
Algorithm Workbench
35. Write a while loop that lets the user enter a number. The number should be multiplied by 10, and the result stored
in the variable product. The loop should iterate as long as product contains a value less than 100.
36. Write a do-while loop that asks the user to enter two numbers. The numbers should be added and the sum
displayed. The user should be asked if he or she wishes to perform the operation again. If so, the loop should repeat;
otherwise it should terminate.
37. Write a for loop that displays the following set of numbers:
0, 10, 20, 30, 40, 50 . . . 1000

38. Write a loop that asks the user to enter a number. The loop should iterate 10 times and keep a running total of the
numbers entered.

40. Convert the following while loop to a do-while loop:


int x = 1;
while (x > 0)
{
cout << "enter a number: ";
cin >> x;
}
41. Convert the following do-while loop to a while loop:
char sure;
do
{
cout << "Are you sure you want to quit? ";
cin >> sure;
} while (sure != 'Y' && sure != 'N');

42. Convert the following while loop to a for loop:


int count = 0;
while (count < 50)
{
cout << "count is " << count << endl;
count++;
}

43. Convert the following for loop to a while loop:


for (int x = 50; x > 0; x−−)
{
cout << x << " seconds to go.\n";
}

True or False
47. T F The operand of the increment and decrement operators can be any valid mathematical expression.
48. T F The cout statement in the following program segment will display 5:
int x = 5;
cout << x++;
49. T F The cout statement in the following program segment will display 5:
int x = 5;
cout << ++x;
50. T F The while loop is a pretest loop.
51. T F The do-while loop is a pretest loop.
52. T F The for loop is a posttest loop.
53. T F It is not necessary to initialize counter variables.

54. T F All three of the for loop’s expressions may be omitted.


55. T F One limitation of the for loop is that only one variable may be initialized in the initialization expression.
56. T F Variables may be defined inside the body of a loop.
57. T F A variable may be defined in the initialization expression of the for loop.
58. T F In a nested loop, the outer loop executes faster than the inner loop.
59. T F In a nested loop, the inner loop goes through all of its iterations for every single iteration of the outer loop.
60. T F To calculate the total number of iterations of a nested loop, add the number of iterations of all the loops.
61. T F The break statement causes a loop to stop the current iteration and begin the next one.
62. T F The continue statement causes a terminated loop to resume.
63. T F In a nested loop, the break statement only interrupts the loop it is placed in.

Programming Challenges
3. Ocean Levels
Assuming the ocean’s level is currently rising at about 1.5 millimeters per year, write a program that displays a table
showing the number of millimeters that the ocean will have risen each year for the next 25 years.
4. Calories Burned
Running on a particular treadmill you burn 3.6 calories per minute. Write a program that uses a loop to display the
number of calories burned after 5, 10, 15, 20, 25, and 30 minutes.
Review Questions and Exercises
Short Answer
1. Why do local variables lose their values between calls to the function in which they are defined?
2. What is the difference between an argument and a parameter variable?
3. Where do you define parameter variables?
4. If you are writing a function that accepts an argument and you want to make sure the function cannot change the
value of the argument, what do you do?
5. When a function accepts multiple arguments, does it matter in what order the arguments are passed?
6. How do you return a value from a function?
7. What is the advantage of breaking your application’s code into several small procedures?
8. How would a static local variable be useful?
9. Give an example where passing an argument by reference would be useful.

Fill-in-the-Blank
10. The _________ is the part of a function definition that shows the function name, return type, and parameter list.
Function header
11. If a function doesn’t return a value, the word _________ will appear as its return type. void
12. Either a function’s _________ or its _________ must precede all calls to the function.
13. Values that are sent into a function are called _________.

14. Special variables that hold copies of function arguments are called _________.
15. When only a copy of an argument is passed to a function, it is said to be passed by _________.
16. A(n) _________ eliminates the need to place a function definition before all calls to the function.
17. A(n) _________ variable is defined inside a function and is not accessible outside the function.
18. ________ variables are defined outside all functions and are accessible to any function within their scope.
19. ________ variables provide an easy way to share large amounts of data among all the functions in a program.
20. Unless you explicitly initialize global variables, they are automatically initialized to _________.
21. If a function has a local variable with the same name as a global variable, only the _________ variable can be seen by
the function.
22. ________ local variables retain their value between function calls.
23. The _________ statement causes a function to end immediately.
24. ________ arguments are passed to parameters automatically if no argument is provided in the function call.
25. When a function uses a mixture of parameters with and without default arguments, the parameters with default
arguments must be defined _________.
26. The value of a default argument must be a(n) _________.
27. When used as parameters, _________ variables allow a function to access the parameter’s original argument.
28. Reference variables are defined like regular variables, except there is a(n) _________ in front of the name.
29. Reference variables allow arguments to be passed by ____________.
30. The _________ function causes a program to terminate.
31. Two or more functions may have the same name, as long as their _________ are different.

Algorithm Workbench
32. Examine the following function header, then write an example call to the function.
void showValue(int quantity)
33. The following statement calls a function named half . The half function returns a value that is half that of the
argument. Write the function.
result = half(number);
34. A program contains the following function.
int cube(int num)
{
return num * num * num;
}

Write a statement that passes the value 4 to this function and assigns its return value to the variable result .
35. Write a function named timesTen that accepts an argument. When the function is called, it should display the
product of its argument multiplied times 10.
36. A program contains the following function.
void display(int arg1, double arg2, char arg3)
{
cout << "Here are the values: "
<< arg1 << " " << arg2 << " "
<< arg3 << endl;
}
Write a statement that calls the procedure and passes the following variables to it:
int age;
double income;
char initial;

True or False
38. T F Functions should be given names that reflect their purpose.
39. T F Function headers are terminated with a semicolon.
40. T F Function prototypes are terminated with a semicolon.
41. T F If other functions are defined before main, the program still starts executing at function main.
42. T F When a function terminates, it always branches back to main, regardless of where it was called from.
43. T F Arguments are passed to the function parameters in the order they appear in the function call.
44. T F The scope of a parameter is limited to the function which uses it.
45. T F Changes to a function parameter always affect the original argument as well.
46. T F In a function prototype, the names of the parameter variables may be left out.
47. T F Many functions may have local variables with the same name.
48. T F Overuse of global variables can lead to problems.
49. T F Static local variables are not destroyed when a function returns.
50. T F All static local variables are initialized to −1 by default.
51. T F Initialization of static local variables only happens once, regardless of how many times the function in which they
are defined is called.
52. T F When a function with default arguments is called and an argument is left out, all arguments that come after it
must be left out as well.
53. T F It is not possible for a function to have some parameters with default arguments and some without.
54. T F The exit function can only be called from main.
55. T F A stub is a dummy function that is called instead of the actual function it represents.

2. Rectangle Area—Complete the Program


Create a program that will ask the user to enter the width and length of a rectangle and then display the rectangle’s
area. The program calls the following functions:
• getLength – This function should ask the user to enter the rectangle’s length and then return that value as a double .
• getWidth – This function should ask the user to enter the rectangle’s width and then return that value as a double .
• getArea – This function should accept the rectangle’s length and width as arguments and return the rectangle’s area.
The area is calculated by multiplying the length by the width.
• displayData – This function should accept the rectangle’s length, width, and area as arguments and display them in an
appropriate message on the screen.

6. Kinetic Energy
In physics, an object that is in motion is said to have kinetic energy. The following formula can be used to determine a
moving object’s kinetic energy:
KE = 1/2 mv2
The variables in the formula are as follows: KE is the kinetic energy, m is the object’s mass in kilograms, and v is the
object’s velocity, in meters per second.
Write a function named kineticEnergy that accepts an object’s mass (in kilograms) and velocity (in meters per second) as
arguments. The function should return the amount of kinetic energy that the object has. Demonstrate the function by
calling it in a program that asks the user to enter values for mass and velocity.

7. Celsius Temperature Table


The formula for converting a temperature from Fahrenheit to Celsius is
C = 5/9 (F - 32)

where F is the Fahrenheit temperature and C is the Celsius temperature. Write a function named celsius that accepts a
Fahrenheit temperature as an argument. The function should return the temperature, converted to Celsius.
Demonstrate the function by calling it in a loop that displays a table of the Fahrenheit temperatures 0 through 20 and
their Celsius equivalents.

Potrebbero piacerti anche