C++ Primer, Chapter 1: Exercise Answers
Working answers for Chapter 1 exercises covering compilation, streams, loops, comments, input validation, and the Sales_item transaction examples.
Contents19 sections
C++ Primer, Fifth Edition — Chapter 1 Answers
These are my working answers to the Chapter 1 exercises. The examples are intentionally basic; later chapters add more detailed explanations as the language features become more interesting.
Exercises 1.1 and 1.2
The smallest valid program returns success:
int main() {
return 0;
}
Returning -1 is also valid, although the operating system observes it as a non-zero failure status:
int main() {
return -1;
}
Exercise 1.3
#include <iostream>
int main() {
std::cout << "Hello, World" << std::endl;
return 0;
}
Exercises 1.4 and 1.5
Read two integers and print their product:
#include <iostream>
int main() {
int left = 0, right = 0;
std::cin >> left >> right;
std::cout << "The product of " << left
<< " * " << right
<< " is " << left * right
<< std::endl;
return 0;
}
Exercise 1.5 produces the same result using several separate output statements instead of one chained expression.
Exercises 1.6–1.8: output and comments
Every continued insertion expression needs a stream on its left. A new statement beginning with << is invalid because there is no left-hand operand.
C-style block comments cannot be nested. Comment delimiters inside string literals are ordinary characters:
std::cout << "/*"; // valid
std::cout << "*/"; // valid
The book's deliberately awkward expressions demonstrate that the compiler distinguishes lexical comments from quoted text.
Exercise 1.9: sum from 50 through 100
#include <iostream>
int main() {
int sum = 0, value = 50;
while (value <= 100) {
sum += value;
++value;
}
std::cout << "The sum from 50 through 100 is " << sum << std::endl;
}
Exercise 1.10: countdown
int value = 10;
while (value >= 0) {
std::cout << value << std::endl;
--value;
}
Exercises 1.11 and 1.19: print a range in either direction
#include <iostream>
int main() {
int first = 0, second = 0;
std::cin >> first >> second;
if (first <= second) {
while (first <= second) {
std::cout << first++ << std::endl;
}
} else {
while (first >= second) {
std::cout << first-- << std::endl;
}
}
}
Exercise 1.12
The sum of every integer from -100 through 100 is zero:
int sum = 0;
for (int value = -100; value <= 100; ++value) {
sum += value;
}
Exercise 1.13
Rewrite the earlier while exercises as for loops. Initialization, condition, and increment can all live in the for header, but any field may be omitted when the state is managed elsewhere.
int sum = 0;
for (int value = 50; value <= 100; ++value) {
sum += value;
}
Exercise 1.14: for versus while
- A
forloop keeps initialization and increment close to the condition, which is concise when the iteration count is known. - A
whileloop often reads more naturally when repetition ends because of an external condition such as input success. - The two forms are functionally equivalent and can be rewritten into each other.
Exercise 1.15: common compiler diagnostics
The exercise demonstrates three broad categories:
- syntax errors;
- type errors;
- declaration errors.
Exercise 1.16: sum an unknown number of values
Stream extraction itself can be the loop condition. Input stops on end-of-file or invalid data.
#include <iostream>
int main() {
int sum = 0, value = 0;
while (std::cin >> value) {
sum += value;
}
std::cout << "The sum is " << sum << std::endl;
}
Exercises 1.17 and 1.18: count consecutive values
#include <iostream>
int main() {
int current = 0, value = 0;
if (std::cin >> current) {
int count = 1;
while (std::cin >> value) {
if (value == current) {
++count;
} else {
std::cout << current << " occurs " << count << " times\n";
current = value;
count = 1;
}
}
std::cout << current << " occurs " << count << " times\n";
}
}
If every input value is equal, one group is printed. If no adjacent values match, each group has count 1.
Exercise 1.20: echo Sales_item values
#include <iostream>
#include "Sales_item.h"
int main() {
Sales_item book;
while (std::cin >> book) {
std::cout << book << std::endl;
}
}
Exercise 1.21: add two transactions
Sales_item first, second;
std::cin >> first >> second;
if (first.isbn() == second.isbn()) {
std::cout << first + second << std::endl;
return 0;
}
std::cerr << "The ISBN values must match" << std::endl;
return -1;
Exercise 1.22: sum several matching transactions
Read the first transaction into total, then add each following transaction while the ISBN remains the same.
Sales_item total;
if (std::cin >> total) {
Sales_item transaction;
while (std::cin >> transaction) {
if (total.isbn() == transaction.isbn()) {
total += transaction;
} else {
std::cout << total << std::endl;
total = transaction;
}
}
std::cout << total << std::endl;
}
Exercise 1.23: count transactions per ISBN
The structure is the same as counting consecutive integers: keep the current ISBN and a count, print the group when the ISBN changes, then reset.
Sales_item current;
if (std::cin >> current) {
int count = 1;
Sales_item transaction;
while (std::cin >> transaction) {
if (current.isbn() == transaction.isbn()) {
++count;
} else {
std::cout << current.isbn() << " occurs " << count << " times\n";
current = transaction;
count = 1;
}
}
std::cout << current.isbn() << " occurs " << count << " times\n";
}
Exercise 1.24: file redirection
The counting program can read from a file and write to another file without changing its C++ stream code:
type book_sales.txt
1.24.exe < book_sales.txt > 1.24.txt
type 1.24.txt
Shell redirection connects the files to standard input and standard output.
Exercise 1.25: the bookstore program
The complete program groups consecutive transactions by ISBN, prints the accumulated item whenever the ISBN changes, and reports an error if no input is available.
#include <iostream>
#include "Sales_item.h"
int main() {
Sales_item total;
if (std::cin >> total) {
Sales_item transaction;
while (std::cin >> transaction) {
if (total.isbn() == transaction.isbn()) {
total += transaction;
} else {
std::cout << total << std::endl;
total = transaction;
}
}
std::cout << total << std::endl;
return 0;
}
std::cerr << "No data" << std::endl;
return -1;
}
The companion Sales_item.h file comes from the official C++ Primer exercise materials. At this stage it is enough to use its stream, ISBN, addition, and accumulation operations; the class implementation is explained in later chapters.
Related posts
Discussion / approved
Comments
No comments yet.