02. Your first C++ program — Homework Solutions
The solution .cpp files are in
exercises/02/homework/solutions/.
Open this page after trying on your own. How to use it: compare your line of reasoning with the How to think about it part, not the code line by line. Two pieces of code with different shapes can both be correct, and what you need to copy is the way of getting there.
Running one of the solutions:
g++ -std=c++17 -O2 -o jawab exercises/02/homework/solutions/01-biodata.cpp
./jawab
Problem 1 — Personal details
Problem. Print four lines of personal details, one
cout per line.
How to think about it. Each output line is one
cout statement ending with endl. No variables,
no logic — the goal is to get your hands used to the
cout << ... << endl; shape and the
semicolon.
Walkthrough.
#include <iostream>
using namespace std;
int main() {
cout << "Nama: Budi Santoso" << endl;
cout << "Kelas: 9A" << endl;
cout << "Sekolah: SMP Negeri 1 Bandung" << endl;
cout << "Saya ingin ikut OSN karena senang memecahkan teka-teki." << endl;
return 0;
}Tests. This program reads no input; its output must be four lines, each containing one detail. Check one thing that is easy to miss: there are no blank lines between them, and no spaces at the end of a line.
endl is used in this chapter because it is the only
thing introduced so far. From Part 3 this book switches to the faster
"\n". For a problem this small the two are the same — what
matters is being consistent within one program.
Common mistakes.
- Forgetting the semicolon at the end of one of the lines.
- Writing
cout << "Nama: Budi" << endlwithout the closing quote, so the compiler complainsmissing terminating " character.
Problem 2 — Name card
Problem. Print a box of +,
-, and | with a name in the middle.
How to think about it. The picture has three lines,
so the code has three couts. The important part:
the top, middle, and bottom lines must have the same
length, otherwise the box is crooked. First count the width of
the content (here 16 characters), then write +, 16
- signs, then +.
Walkthrough.
cout << "+----------------+" << endl;
cout << "| Budi Santoso |" << endl;
cout << "+----------------+" << endl;Tests. Count the length of the three lines by hand — all three must be exactly the same:
| Line | Length |
|---|---|
+----------------+ |
1 + 16 + 1 = 18 |
| Budi Santoso | |
1 + 16 + 1 = 18 |
+----------------+ |
1 + 16 + 1 = 18 |
If your name is longer or shorter than Budi Santoso,
the number of - signs must be adjusted along with it. This
is why this problem forbids loops for now: so you feel how tedious it is
to match widths by hand, and how easy it is after Chapter 05.
Common mistakes.
- The number of
-on the top and bottom lines differs. - Counting the length of the middle line without accounting for spaces.
Problem 3 — Table with tabs
Problem. Print a table of the names and scores of
three friends with \t as the separator.
How to think about it. \t jumps to the
next tab position, rather than adding a fixed number of spaces. That is
why the columns look aligned as long as the names are the same length or
differ by no more than one tab jump.
Walkthrough.
cout << "Nama\tNilai\n";
cout << "Budi\t90\n";
cout << "Siti\t85\n";
cout << "Andi\t78\n";Tests. The output:
Nama Nilai
Budi 90
Siti 85
Andi 78
Tab positions in a terminal are usually multiples of 8 characters.
Because Nama, Budi, Siti, and
Andi are all four letters, one \t is enough to
jump to the same column. Try changing one name to Muhammad
and see the column shift by one jump.
Common mistakes.
- Writing
\toutside the quotes. - Using names whose lengths differ a lot (
Muhammad RizkiandAni), then wondering why the columns do not line up. That case needssetwfrom<iomanip>, which is not used in this chapter yet.
Problem 4 — Fix the errors
Problem. A file deliberately broken with three mistakes.
How to think about it. Fix one mistake, the topmost, then compile again. One mistake often produces many lines of messages, so fixing everything at once based on guesses usually adds more problems.
The three mistakes:
using namespace stdwithout a semicolon.Coutshould becout— C++ distinguishes upper and lower case.- No semicolon after
endl.
The first compile gives two messages at once:
04-perbaiki-error.cpp:11:20: error: expected ';' before 'int'
11 | using namespace std
| ^
| ;
04-perbaiki-error.cpp: In function 'int main()':
04-perbaiki-error.cpp:14:5: error: 'Cout' was not declared in this scope
14 | Cout << "Semua error sudah diperbaiki." << endl
| ^~~~
Notice that the third mistake has not appeared at all
yet. The compiler stops understanding the body of
main as soon as it meets the unknown Cout, so
it has not yet got as far as checking the semicolon after
endl. Only after the first two mistakes are fixed and the
code is compiled again does this appear:
04-perbaiki-error.cpp:14:52: error: expected ';' before 'return'
This is the correct way to work: fix the topmost one, compile again, read the new message. Trying to guess all three at once from the first message is impossible, because the third message does not exist yet.
Walkthrough.
#include <iostream>
using namespace std;
int main() {
cout << "Semua error sudah diperbaiki." << endl;
return 0;
}Common mistakes.
- Panicking at a long error message. The first message is almost always the real one; the rest are consequences.
- Deleting the line with the error instead of fixing it.
Challenge — Nested quotes
Problem. Print
Guru berkata: "tulis \n untuk pindah baris" as-is.
How to think about it. There are two kinds of
characters that need to be escaped: a double quote becomes
\", and a backslash becomes \\. The trap is
the \n inside the sentence: if written as-is, it turns into
a line break. For it to appear as the two characters \ and
n, write \\n.
Walkthrough.
cout << "Guru berkata: \"tulis \\n untuk pindah baris\"" << endl;Tests. The output is exactly one line:
Guru berkata: "tulis \n untuk pindah baris"
If your output is split into two lines, the \n inside
the sentence is still being read as a line break command, not as two
ordinary characters.
Common mistakes.
- Writing
\ninstead of\\n, so the sentence is cut into two lines. - Forgetting the
\on a quote, so the compiler thinks the text has ended and complainsexpected ';'.
OSN-style exercises — walkthrough
The solution files are in
exercises/02/osn/solutions/.
Problem 1 — Chessboard
How to think about it. An 8 × 8 board has only two
row shapes: #.#.#.#. and .#.#.#.#. They
alternate, starting with the first shape. Without loops, the answer is
eight cout statements.
Walkthrough.
cout << "#.#.#.#.\n";
cout << ".#.#.#.#\n";
cout << "#.#.#.#.\n";
cout << ".#.#.#.#\n";
cout << "#.#.#.#.\n";
cout << ".#.#.#.#\n";
cout << "#.#.#.#.\n";
cout << ".#.#.#.#\n";Tests. There must be exactly eight lines and each line exactly eight characters. A quick way to check this in the terminal:
./catur | wc -l
./catur | awk '{ print length($0) }'
The first command must print 8, the second eight
8s.
Common mistakes.
- Swapping the order of the rows, so the top-left corner becomes
.. - Writing nine lines because the last line gets an extra
endl.
Problem 2 — Staircase
How to think about it. Line i consists
of 5 - i spaces followed by i #
signs, so the length of every line is always five. Counting the spaces
is easier from the bottom: the last line has no spaces at all.
Walkthrough.
cout << " #\n";
cout << " ##\n";
cout << " ###\n";
cout << " ####\n";
cout << "#####\n";Tests. Every line must have length five:
./tangga | awk '{ print length($0) }'
If any number other than 5 appears, the number of spaces
is wrong — or a space has slipped in at the end of a line.
Common mistakes.
- Writing a left-aligned staircase (
#,##,###) when the problem asks for a right-aligned one. - Adding spaces at the end of lines so it "looks tidy" in the editor.
Problem 3 — Shop Receipt
How to think about it. Each of the three troublesome
characters has its own escape form: \t for a tab,
\" for a quote, \\ for a single backslash. The
path C:\struk\2026.txt contains two backslashes, so in the
code it is written C:\\struk\\2026.txt.
Walkthrough.
cout << "Toko\t\"Sumber Rejeki\"\n";
cout << "Berkas\tC:\\struk\\2026.txt\n";
cout << "Pensil\t3\t6000\n";
cout << "Buku\t2\t14000\n";Tests. Tabs are not visible on screen, so check with
cat -A:
./struk | cat -A
Every tab appears as ^I and every line end as
$. The first line must read
Toko^I"Sumber Rejeki"$.
Common mistakes.
- Replacing the tab with several spaces because they look the same on screen.
- Writing
C:\strukin the code:\sis not a recognized escape, and the compiler complainsunknown escape sequence. - Forgetting one
\on the closing quote, so the whole rest of the line is treated as part of the text.
If you are still stuck
- Cannot read an error message → Chapter 02, section Reading error messages.
- Confused about when to use
endland when"\n"→ Chapter 02, section Printing withcout. - Quotes and backslashes are confusing → Chapter 02, the Special characters table.
Before moving on to Chapter 03, make sure you can write the complete program skeleton from memory, without copying, in less than one minute.