Chapter 02
Drill
After each step of this drill, run your program to make sure it is really doing what you expect it to. Keep a list of what mistakes you make so that you can try to avoid those in the future.
- Write a program that produces a simple form letter based on user input. Begin by typing the code from §2.1 prompting a user to enter his or her first name and writing “Hello, first_name” where first_name is the name entered by the user. Then modify your code as follows: change the prompt to “Enter the name of the person you want to write to” and change the output to “Dear first_name,”. Don’t forget the comma.
- Add an introductory line or two, like “How are you? I am fine. I miss you.” Be sure to indent the first line. Add a few more lines of your choosing – it’s your letter.
- Now prompt the user for the name of another friend and store it in friend_name. Add a line to your letter: “Have you seen friend_name lately?”
- Prompt the user to enter the age of the recipient and assign it to an int variable age. Have your program write “I hear you just had a birthday and you are age years old.” If age is 0 or less or 110 or more, call simple_error(“you’re kidding!”) using simple_error() from PPP_support.
- Add this to your letter: If your friend is under 12, write “Next year you will be age+1.” If your friend is 17, write “Next year you will be able to vote.” If your friend is over 70, write “Are you retired?” Check your program to make sure it responds appropriately to each kind of value.
- Add “Yours sincerely,” followed by two blank lines for a signature, followed by your name.
Ans:
#include <iostream>
int main() {
std::cout << "Enter the name of the person you want to write to " << std::endl;
std::string first_name;
std::cin >> first_name;
std::cout << "Enter the name of another friend: ";
std::string friend_name;
std::cin >> friend_name;
std::cout << "Enter the age of the recipient: ";
int age = -1;
std::cin >> age;
std::cout << "Dear " << first_name << ",\n";
std::cout << "\tHow are you? I am fine. I miss you. I hope you are doing well.\n";
std::cout << "Have you seen " << friend_name << " lately?\n";
if (age <= 0 || age >= 110) {
std::cerr << "You're kidding!\n";
return 1;
}
std::cout << "I hear you just had a birthday and you are " << age << " years old.\n";
if (age < 12) {
std::cout << "Next year you will be " << age + 1 << ".\n";
} else if (age == 17) {
std::cout << "Next year you will be able to vote.\n";
} else if (age > 70) {
std::cout << "I hope you are enjoying retirement.\n";
}
std::cout << "Yours sincerely,\n\n\n";
std::cout << "Luping\n";
return 0;
}
Review
-
What is meant by the term prompt?
Ans: A prompt is a message displayed to the user, often in the terminal or console, requesting them to input data.
-
Which operator do you use to read into a variable?
Ans: The
>>operator, known as the extraction operator, is used withcinin C++ to read input into a variable. -
What notations can you use to initialize an object?
Ans:
- Direct initialization:
ClassName obj(args); - Uniform initialization:
ClassName obj{args}; - Default initialization:
ClassName obj;
- Direct initialization:
-
If you want the user to input an integer value into your program for a variable named number, what are two lines of code you could write to ask the user to do it and to input the value into your program?
Ans:
#include <iostream> int main() { int int_number std::cout << "Enter an INTEGER"; // <--This line and the follows std::cin >> int_number; return 0; } -
What is
\ncalled and what purpose does it serve?Ans:
\nis called a newline character. It moves the cursor to the next line in the output. -
What terminates input into a string?
Ans: Input into a string is typically terminated by whitespace (spaces, tabs, or newlines) when using
cin. -
What terminates input into an integer?
Ans: Input into an integer is terminated by any non-numeric character (like whitespace or newline).
-
How would you write the following as a single line of code:
cout << "Hello, ";cout << first_name;cout << "!\n";Ans:
cout << "Hello, " << first_name <<"!\n"; -
What is an object?
Ans: An object is an instance of a class, encapsulating data and the methods that operate on that data.
-
What is a literal?
Ans: A literal is a constant value used directly in the code, like
42(integer literal),'a'(character literal), or"hello"(string literal). -
What kinds of literals are there?
Ans:
- Integer literals:
42,0x2A - Floating-point literals:
3.14,2.5e2 - Character literals:
'a','\n' - String literals:
"hello" - Boolean literals:
true,false
- Integer literals:
-
What is a variable?
Ans: A variable is a named storage location in memory that holds a value which can be changed during program execution.
-
What are typical sizes for a
char, anint, and adouble?Ans:
- char: 1 byte
- int: 4 bytes (on most systems)
- double: 8 bytes
-
What measures do we use for the size of small entities in memory, such as ints and strings?
Ans: Memory size is typically measured in bytes.
-
What is the difference between
=and==?Ans:
=is the assignment operator, while==is the equality comparison operator. -
What is a definition?
Ans: A definition specifies the details of an entity like a variable or function, reserving memory and providing implementation.
-
What is an initialization and how does it differ from an assignment?
Ans: Initialization assigns a value to a variable at the time of its creation. Assignment gives a variable a new value after it has been created.
-
What is string concatenation and how do you make it work in C++?
Ans: String concatenation is combining two strings into one. In C++, it is done using the
+operator. For example:string result = "Hello, " + "World!"; -
What operators can you apply to an
int?Ans:
- Arithmetic operators: +, -, *, /, %
- Relational operators: ==, !=, <, >, <=, >=
- Logical operators: &&, ||, !
- Bitwise operators: &, |, ^, ~, «, »
-
Which of the following are legal names in C++? If a name is not legal, why not?

Ans:
-
Give five examples of legal names that you shouldn’t use because they are likely to cause confusion.
Ans:
l(looks like 1)O(looks like 0)temp(too vague)data(too generic)a1(not descriptive)
-
What are some good rules for choosing names?
Ans:
-
What is type safety and why is it important?
Ans: Type safety ensures that operations on data are performed only on compatible types, preventing runtime errors and undefined behavior.
-
Why can conversion from double to int be a bad thing?
Ans: It can lead to loss of precision, as the fractional part of the double is truncated.
-
Define a rule to help decide if a conversion from one type to another is safe or unsafe.
Ans: A conversion is safe if it preserves all possible values of the source type. It is unsafe if it can cause truncation, overflow, or loss of information.
-
How can we avoid undesirable conversions?
Ans:
- Use explicit casting.
- Enable compiler warnings.
- Use stricter type-checking.
-
What are the uses of
auto?Ans:
- Simplifies variable declarations.
- Enables type inference.
- Helps make code more concise and readable. For example:
auto x = 42; // x is of type int auto y = 3.14; // y is of type double
Chapter 03
Drill
- Now change the body of the loop so that it reads just one double each time around. Define two variables to keep track of which is the smallest and which is the largest value you have seen so far. Each time through the loop write out the value entered. If it’s the smallest so far, write the smallest so far after the number. If it is the largest so far, write the largest so far after the number.
- Add a unit to each double entered; that is, enter values such as 10cm, 2.5in, 5ft, or 3.33m. Accept the four units: cm, m, in, ft. Assume conversion factors 1m==100cm, 1in==2.54cm, 1ft==12in. Read the unit indicator into a string. You may consider 12 m (with a space between the number and the unit) equivalent to 12m (without a space).
- Reject values without units or with “illegal” representations of units, such as y, yard, meter, km, and gallons.
- Keep track of the sum of values entered (as well as the smallest and the largest) and the number of values entered. When the loop ends, print the smallest, the largest, the number of values, and the sum of values. Note that to keep the sum, you have to decide on a unit to use for that sum; use meters.
- Keep all the values entered (converted into meters) in a vector. At the end, write out those values.
- Before writing out the values from the vector, sort them (that’ll make them come out in increasing order).
Ans
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
double value;
double smallest, largest;
std::string unit;
double sum = 0;
std::vector<double> values;
bool first_input = true; // used to mark if it is the first input
std::cout << "Enter numbers (type a non-numeric value to stop):" << std::endl;
while (std::cin >> value >> unit)
{
std::cout << "You entered: " << value << " " << unit;
if (unit == "cm")
{
value /= 100;
std::cout << " (converted to m)";
}
else if (unit == "in")
{
value *= 0.0254;
std::cout << " (converted to m)";
}
else if (unit == "ft")
{
value *= 0.3048;
std::cout << " (converted to m)";
}
else if (unit == "m")
{
// do nothing
}
else
{
std::cout << " (invalid unit)" << std::endl;
continue;
}
if (first_input)
{
// initialize smallest and largest when first input
smallest = largest = value;
first_input = false;
}
sum += value;
values.push_back(value);
// check if it is the smallest value
if (value < smallest)
{
smallest = value;
std::cout << " (smallest so far)";
}
// check if it is the largest value
if (value > largest)
{
largest = value;
std::cout << " (largest so far)";
}
std::cout << std::endl;
}
if (!first_input)
{
// if there is valid input, output the result
std::cout << "End of input. Smallest value: " << smallest << ", Largest value: " << largest << std::endl;
std::cout << "The sum of you entered is " << sum << " m." << std::endl;
}
else
{
// if no valid input
std::cout << "No valid input provided." << std::endl;
}
// before output, sort the values
std::ranges::sort(values);
// Ouputs the sorted values
for (double v : values)
{
std::cout << v << " m" << std::endl;
}
return 0;
}
Review
- What is a computation?
Ans: A computation is a sequence of steps or instructions performed by a computer to solve a problem, transform data, or produce a desired output. It involves processing input data, applying algorithms or calculations, and generating results.
- What do we mean by inputs and outputs to a computation? Give examples.
Ans:
- inputs are the data or values provided to a computation to process.
- Outputs are the results generated after processing the inputs.
- Examples:
- Input: A list of numbers, Output: Their sum.
- Input: A text string, Output: The number of words in the string.
- What are the three requirements a programmer should keep in mind when expressing computations?
Ans:
- Correctness: The computation must achieve the intended result.
- Clarity: The code should be readable and understandable.
- Efficiency: The computation should use resources like time and memory efficiently.
- What does an expression do?
Ans: An expression evaluates to a value. It performs calculations or operations and produces a result.
Example: 3 + 5 evaluates to 8.
- What is the difference between a statement and an expression, as described in this chapter?
Ans:
- Expression: Produces a value (e.g., x + y).
- Statement: Performs an action, such as declaring a variable or making a decision (e.g., int x = 10; or if (x > y)).
- What is an
lvalue? List the operators that require anlvalue. Why do these operators, and not the others, require an value?
Ans: An lvalue (locator value) is an expression that refers to a memory location, allowing assignment. Operators requiring lvalue: =, ++, –, &. These operators modify or reference the memory location, so they need an lvalue.
- What is a constant expression?
Ans: A constant expression is an expression whose value is known and fixed at compile time. Example: 3 + 5 or 4 * 2.
- What is a literal?
Ans: A literal is a fixed value written directly in code. Examples:
- Integer: 42
- Floating-point: 3.14
- String: “hello”
- What is a symbolic constant and why do we use them?
Ans: A symbolic constant is a named value defined using const or constexpr. It improves readability and maintainability. Example: const double pi = 3.14;
- What is a magic constant? Give examples.
Ans: A magic constant is a hard-coded, unexplained number in code. Example: if (x == 42) // Why 42?. Avoid magic constants by using symbolic constants.
- What are some operators that we can use for integers and floating-point values?
Ans:
- What operators can be used on integers but not on floating-point numbers?
Ans: Bitwise operators: &, |, ^, ~, <<, >>
- What are some operators that can be used for strings?
Ans:
- Concatenation:
+ - Comparison:
==,!=,<,>,<=,>=
- When would a programmer prefer a switch-statement to an if-statement?
Ans: When checking a single variable against multiple constant values, switch is often more readable and efficient.
- What are some common problems with switch-statements?
Ans:
- Forgetting a
breakstatement. - Lack of type safety (only works with integers, enums, and certain types).
- What is the function of each part of the header line in a for-loop, and in what sequence are they executed?
Ans:
for (initialization; condition; update)
- Initialization: Executes once before the loop.
- Condition: Checked before each iteration.
- Update: Executes after each iteration.
- When should the for-loop be used and when should the while-loop be used?
Ans:
- For-loop: Use when the number of iterations is known.
- While-loop: Use when the loop runs based on a condition rather than a count.
- Describe what the line
char foo(int x)means in a function definition.
Ans:
- When should you define a separate function for part of a program? List reasons.
Ans:
- When code is reused multiple times.
- To improve readability.
- To simplify debugging.
- To encapsulate a specific task.
- What can you do to an
intthat you cannot do to astring?
Ans:
- What can you do to a
stringthat you cannot do to anint?
Ans: Concatenate strings, access individual characters using indices, or calculate string length.
- What is the index of the third element of a vector?
Ans:
- How do you write a for-loop that prints every element of a vector?
Ans:
for (auto elem : my_vector) {
std::cout << elem << " ";
}
- What does
vector<char> alphabet(26);do?
Ans:
- Describe what
push_back()does to a vector.
Ans:
- What does vector’s member
size()do?
Ans:
- What makes vector so popular/useful?
Ans:
- Dynamic resizing.
- Easy access with indexing.
- Standard library functions like sort.
- How do you sort the elements of a vector?
Ans:
#include <algorithm>
std::sort(my_vector.begin(), my_vector.end());
// Or
std::ranges::sort(my_vector) // It works using c++20