- b
- a
- b
- c
- a
- a or b
- d
- c
- a, b, c, and d all work
- b
- c; Many programmers call this a do loop, while others call it a do-while loop. It is a test-at-the-bottom loop, so the body is executed at least once.
- all work; strictly speaking, C++ syntax does not require the { and } for a one-statement do-while loop, but most programmers often use them anyway. The first two are harder to understand but will work.
- both a and b work; but a is much closer to the original problem statement and is therefore preferred.
- d; When the program terminates, which it does when the program calls exit, it does exit any executing loop, block, or function, but the intended meaning should be clear.
- a
- either a or b
- a; The two related functions, _getch and _getche, are non-ANSI (and therefore not portable) functions used primarily on Windows. The 'e' in _getche stands for echo - it echos or prints the character on the screen; _getch reads a character but does not display it on the screen.
- all work; The default statement may be anywhere inside the switch (but it is most often placed at the bottom). The "break" is technically not needed after the last case or default, but I think it is good practice to put a break at the end (so, when you or the next programmer adds a new case, the break is not accidentally forgotten).
- They all work! However, anytime one of the expressions is more complex than a single constant or a single variable, you should enclose the expression in parentheses. The conditional operator has low precedence, and the parentheses prevent precedence errors and improve readability.
- a or b; b also works because the order is not important in this example. Watch out for c and d: these statements will compile and run but won't produce the desired results.
- d
- b
- b; You cannot define two variables with the same name in the same scope, The code fragment defines two variables, both named x, but the variables are in different scopes. The braces define a new block, which creates a new scope, which is closed by '}' (which "hides" x = 5). You would not ordinarily create a new block without a good reason. And you should avoid giving two variables the same name so close together.
- a; The code defines two variables named x within two distinct scopes, so the code is correct (but see the comment above).
- c
- d
- c
- c
- a
- b; ANY data type can serve as a Boolean value: 0 is false, non-zero is true.
- b; Two symbols, '?' and ':', form the conditional operator, which is similar to an if-statement. The operator has three operands that appear between the two symbols: a ? b : c. If 'a' evaluates to non-zero, then the value of the statement is 'b'; otherwise, the statement evaluates to 'c'. If any of a, b, or c are more complex than constants or single variables, programmers typically place them in parentheses.
- a; Programmers can compare different data types if the compiler can automatically convert or promote one type to the other.
- c; Indentation helps make the code easier for people to read but does not otherwise affect the program's meaning. The first cout statement is part of the for-loop, but the second cout statement is outside of the loop and only executed once.
- b; This is an example of the infamous dangling-else problem. Indentation suggests that the "else" is associated with the first if-statement, but without braces, the "else" is associated with the nearest if-statement - the second if-statement in this problem.
- e
- b
- c
- a; The while loop is a test-at-the-top - this means that the test takes place before execution enters the loop; if the test is false, the program skips the loop.
- a; The for loop is a test-at-the-top - this means that the test takes place before execution enters the loop; if the test is false, the program skips the loop.
- b; The do-while loop is a test-at-the-bottom - this means that the loop always executes at least once before evaluating the test expression. The loop will continue to run as long as the expression in the parentheses following while is true. counter is initialized to 100 above the loop and decremented once before the loop reaches the test. So, the first time the loop evaluates the test, it is
while (99 < 10)
. The expression 99 < 10 is false and the loop ends after running once.
- f; None of the cases match so the default executes. Programmers generally place the default at the bottom of the switch, but it can appear anywhere inside the switch.
- e; Execution beings once a case matches the test value and continues to the next break or the bottom of the switch, whichever comes first.
- d; For each value of i, 0 to 9, the inner for loop runs 10 times (j equals 0 to 9). So the cout statement runs 10 x 10 times.
- 0. Executing a break inside a loop skips all statements between the break and the loop-bottom, and ends the loop. So, the outer for-loop sets i = 0. if (i == 0) is true, the break statement ends the outer loop, skipping the inner loop and the cout statement altogether.
- 90. Executing a continue inside a loop skips all statements between the continue and the loop-bottom, but it doesn't end the loop. So, the outer for-loop sets i = 0. if (i == 0) is true, the continue skips the inner loop. The outer loop increments i to 1 and runs 9 more times. For each run of the outer loop, the inner loop runs 10 times.
- 1. An extraneous ';' at the end of the while forms a null statement - the while loop runs 10 times but does nothing. Although the cout statement is indented, it is not part of the while loop and runs once when the while-loop is finished.
- b. Notice the ';' at the end of the first line? That creates a "null statement" that effectively means that the for-loop does nothing; the cout statement executes once when the for loop finishes.
- b. Notice the ';' at the end of the second line? That creates a "null statement" that effectively means that the while-loop does nothing; the statements inside the braces execute once when the while loop finishes.
- f. The variable i is defined inside the do-while body (i.e., inside the braces), which forms a block, which in turn creates a distinct scope. The variable i in the expression
i < 10
is outside the body or block. So, i in the test expression is out of scope, preventing the code from compiling.
for (int i = 0; i <= 10; i += 2)
cout << i << endl;
for (int i = 0; i < 11; i += 2)
cout << i << endl;
for (int i = 0; i <= 10; i = i + 2)
cout << i << endl;
for (int i = 0; i < 11; i = i + 2)
cout << i << endl;
There are other possible solutions, but these are the most straightforward. Some common errors:
i+2
does not change the value stored in i
i < 10
does not include "10" in the output
for (int i = 10; i >= 0; i -= 2)
cout << i << endl;
for (int i = 10; i >= 0; i = i - 2)
cout << i << endl;
Again, other possible solutions exist, but these are the clearest. Some common errors:
i-2
does not change the value stored in i
i > 0
does not include "0" in the output
- The problem here is very similar to a demonstration program in the text, and you could almost copy the example for the answer to the question, but they are different problems. You must understand the two problems - how are they similar and how are they different - so you know what part of the example code pertains to the current problem. Some general comments:
- Read the question carefully so that your program solves the required problem
- Make the solution general: users may enter 0 or more values - don't assume a fixed number of entries
- Users may enter -1 at the first prompt (i.e. they may not enter any data at all)
- Keep your program as simple as possible. Don't include unneeded structures like arrays or vectors
- Avoid confusing constructs like
for (int i = 1; i > 0; ++i)
. This code results in an infinite or unending loop, but there are better and more common options:
while (true)
while (1)
for (;;)
- Avoid nested loops when they are not needed
- Don't write tests that have overlapping conditions (e.g.,
score != -1 && score >= 0
if score > 0, then it can't possibly be -1)
- Don't include unneeded statements or variables; it is especially easy to do this when you copy code you don't fully understand. For example, if you copied code from the similar demonstration program, it's easy to include the variable counter into this program where it isn't needed.
- Don't include dead or unreachable code
- Put everything you need in the program, but need everything you put in the program.
- <cmath> and define _USE_MATH_DEFINES are not needed
- Don't print an error message when users enter a -1; that's how they end the program and so is valid input
- If you use "exit," remember that it is a function that requires an argument: exit(0); and that it ends the program (following statements are not executed)
#include <iostream>
using namespace std;
int main()
{
int score;
int sum = 0;
cout << "Enter a score (-1 to end): ";
cin >> score;
while (score != -1)
{
sum += score;
cout << "Enter a score (-1 to end): ";
cin >> score;
}
cout << "The total is " << sum << endl;
return 0;
}
Or
#include <iostream>
using namespace std;
int main()
{
int score;
int sum = 0;
while (true)
{
cout << "Enter a score (-1 to end): ";
cin >> score;
if (score == -1)
break;
sum += score;
}
cout << "The total is " << sum << endl;
return 0;
}
Or
#include <iostream>
using namespace std;
int main()
{
int score;
int sum = 0;
do
{
cout << "Enter a score (-1 to end): ";
cin >> score;
if (sore == -1)
break;
sum += score;
}
while (score != -1);
cout << "The total is " << sum << endl;
return 0;
}