02. Your first C++ program

The shortest useful C++ program has six lines. This chapter dissects all six, then adds comments and how to read your first error messages.

The basic shape

#include <iostream>
using namespace std;

int main() {
    cout << "Halo, OSN!" << endl;
    return 0;
}

Compile and run:

g++ -std=c++17 -O2 -o halo exercises/02/01-halo.cpp
./halo

Output:

Halo, OSN!

Now line by line.

Line What it does
#include <iostream> brings in the input/output library, the source of cout and cin
using namespace std; lets standard library names be written without std::
int main() { start of the main function, where the program begins running
cout << "Halo, OSN!" << endl; prints text then moves to a new line
return 0; tells the system that the program finished without problems
} end of the main function

Now those six lines are dissected more deeply, because you will type this skeleton hundreds of times.

#include <iostream>. The # sign marks a command for the preprocessing stage from Chapter 01: before the code is translated, the contents of the file iostream are copied to where this line is. It contains the declarations of cout and cin. Without this line, the compiler does not know what cout is and rejects it with 'cout' was not declared in this scope. An #include line does not end with a semicolon — it is not a C++ statement, but a command for the preprocessor.

using namespace std;. The standard library puts all its names inside one name container called std, so they do not clash with names you create yourself. The full name of cout is actually std::cout. This line says "if there is a name I do not recognize, also look for it inside std", so std:: can be left out.

int main(). The operating system needs one entry point: one function that is run first. In C++ it is always called main. The word int in front of it means main returns an integer to the operating system, and the parentheses () are its parameter list — empty, because main in this book takes nothing.

Curly braces { }. A pair of curly braces marks a block: a group of statements treated as one unit. The body of main is a block. Later, if, for, and other functions also use blocks of the same shape. Every { must have a matching }.

return 0;. The number returned by main is called the exit code: 0 means "finished without problems", any other value means something went wrong. Online judges read this number — a program that ends with a code other than 0 is judged Runtime Error even if its output is already correct.

This five-line skeleton is the same for almost every OSN problem. Retype it from scratch every time you practice, do not copy-paste it, until your fingers know it by heart. Participants who have to think before writing the skeleton lose time in the first minute of the contest, exactly when the mind is at its freshest.

Three things to remember from now on:

  • Every statement ends with a semicolon (;). This is the most frequent cause of errors for beginners.
  • main is always there. A program without main cannot be compiled.
  • Upper and lower case are distinguished. Cout is not cout, Main is not main.

using namespace std; is used throughout this book because it shortens code, and in programming contests short code is faster to write. In large software projects, many people choose to write std::cout in full. Both are correct.

Printing with cout

cout is an "output stream". The << operator pushes a value into that stream. Several values can be pushed in one statement:

int nilai = 90;
cout << "Nilai: " << nilai << endl;

Output:

Nilai: 90

endl moves the cursor to a new line. The alternative is to write "\n" inside the text:

cout << "baris satu\n";
cout << "baris dua\n";

The difference: endl also forces the output to be written immediately (flush), while "\n" does not. For problems with a very large amount of output, "\n" is faster. This book uses "\n" from Part 3 onward.

Without endl or "\n", the output sticks together on one line:

cout << "Halo";
cout << "OSN";
HaloOSN

Text and values are two different things

Anything inside double quotes is printed as-is. Anything outside them is evaluated first, and then printed:

cout << "1 + 2" << "\n";     // text
cout << 1 + 2 << "\n";       // calculation
1 + 2
3

The opposite mistake also happens often: printed values run together because no space was printed along with them. Spaces between << are not printed — a space must be written as text:

int a = 3, b = 4;
cout << a << b << "\n";        // 34
cout << a << " " << b << "\n"; // 3 4

Open exercises/02/02-baris-dan-spasi.cpp. Delete one endl, recompile, and see how two lines stick together into one.

Special characters

Some characters cannot be written directly inside quotes. For those there are escapes: a backslash followed by one letter:

Write Result on screen
\n new line
\t one tab
\" a double quote
\\ a single backslash
cout << "Dia berkata \"siap\"\n";
cout << "Nama:\tBudi\n";
cout << "Folder: C:\\osn\n";
Dia berkata "siap"
Nama:   Budi
Folder: C:\osn

Comments

Comments are notes for humans; the compiler skips them.

// single-line comment

/* comment
   spanning several lines */

In a contest, comments are used to record the idea of the solution, not to translate the code line by line. Compare:

// adds 1 to i                <- useless
i++;

// the remainder is used so the value stays below 1e9+7
hasil %= MOD;

Open exercises/02/03-komentar.cpp. Turn one line of code into a comment by adding // in front of it, recompile, then notice which line disappears from the output.

Reading error messages

The compiler rejects code that is written incorrectly, and prints a message. The message is long, but the important part is always at the start: the file name, the line number, the column number, and the description.

An example of incorrect code:

#include <iostream>
using namespace std;

int main() {
    cout << "Halo" << endl
    return 0;
}

The message looks roughly like this:

error.cpp: In function 'int main()':
error.cpp:5:28: error: expected ';' before 'return'
    5 |     cout << "Halo" << endl
      |                            ^
      |                            ;
    6 |     return 0;
      |     ~~~~~~

How to read it:

  1. error.cpp:5:28 — file error.cpp, line 5, column 28.
  2. expected ';' before 'return' — the compiler wants a semicolon before return.
  3. The ^ sign points at the position.

Notice: the mistake is on line 5, but the compiler only noticed it when it reached line 6. So if the line being pointed at looks correct, check the line above it.

Three messages you will run into often:

Message Meaning
expected ';' before ... a semicolon is missing
'x' was not declared in this scope a variable is used before it is created, or is misspelled
expected '}' at end of input a closing curly brace is missing

The compiler can print dozens of error lines from one mistake. Always fix the topmost error first, then compile again. Often the rest disappear along with it.

A second example, wrong upper/lower case:

int nilai = 90;
cout << Nilai << "\n";
salah.cpp: In function 'int main()':
salah.cpp:6:13: error: 'Nilai' was not declared in this scope; did you mean 'nilai'?
    6 |     cout << Nilai << "\n";
      |             ^~~~~
      |             nilai

The compiler even guesses what you meant on the last line: did you mean 'nilai'. The message was not declared in this scope almost always means one of three things — a misspelling, wrong upper/lower case, or the variable really has not been created yet.

A third example, a missing closing curly brace:

salah2.cpp: In function 'int main()':
salah2.cpp:6:14: error: expected '}' at end of input
    6 |     return 0;
      |              ^
salah2.cpp:4:12: note: to match this '{'
    4 | int main() {
      |            ^

Notice the note: line below it: the compiler shows which { has no match yet. The note: line is often more useful than the error: line itself, so do not stop reading at the first line.

A habit that speeds everything up: compile every time you finish writing five to ten lines, do not wait until the whole program is done. One mistake among ten new lines is easy to find; three mistakes among eighty lines cover each other up and produce confusing messages.

Most common mistakes

What was written What happens
missing semicolon expected ';' before ... on the next line
Cout, Main, Int was not declared in this scope
#include <iostream>; no semicolon is needed on an #include line
opening quote with no closing quote missing terminating " character
{ without } expected '}' at end of input
cout << Halo; (no quotes) treated as a variable name, not text
cout >> x; wrong arrow direction; cout uses <<

OSN tips

Output is compared character by character. The judging machine does not read your intent; it compares your output file with the answer file. That is why these three things all result in Wrong Answer: different upper/lower case, missing or extra spaces, and a missing newline. Many judges forgive trailing spaces at the end of a line, but not all — do not rely on the machine's generosity.

Never print a lead-in sentence. A contest program does not talk to a human. cout << "Masukkan angka: "; is the mistake that most often gets a correct answer rejected, because that sentence ends up in the output file.

Check your output with a machine's eyes. In a Linux terminal, ./program | cat -A shows tabs as ^I and line ends as $, so hidden spaces become visible. An even better way: save the expected output to a file, then compare automatically.

./program > keluaran-saya.txt
diff keluaran-saya.txt keluaran-benar.txt

If diff prints nothing, the two files are identical. This habit saves a lot of time compared to comparing by eye.

One file, one problem. Each problem is submitted as one self-contained .cpp file. No supporting files, no folders, no file reading or writing. A program that opens a file with a fixed name will fail on the judging machine.

return 0; is not decoration. An exit code other than 0 is judged Runtime Error, even if all of its output is correct. In C++17 main may omit return 0; — the compiler adds it by itself — but writing it is still a good habit, because it makes the program's end point visible.

endl forces output to be written to the system every time it is called. For problems that print hundreds of thousands of lines, the habit of using endl can turn a program that should be fast into Time Limit Exceeded. Get used to "\n"; use endl only when you really need to force a flush.

Summary

  • The required skeleton of every program: #include <iostream>, using namespace std;, int main() { ... return 0; }.
  • cout << nilai; prints; << can be chained many times in one statement.
  • Inside quotes is printed as-is, outside quotes is evaluated first.
  • "\n" and endl both move to a new line; "\n" is faster for large output.
  • Escapes to memorize: \n, \t, \", \\.
  • Read error messages from the top, pay attention to the line and column numbers, and also check the line above the one being pointed at.

Homework

Problem 1 — Personal details

Open exercises/02/homework/01-biodata.cpp. Print four lines: your name, grade, school, and one sentence on why you want to take part in OSN. Use one cout statement for each line.

Problem 2 — Name card

Open exercises/02/homework/02-kartu-nama.cpp. Print a box made of the characters +, -, and | with your name in the middle, for example:

+----------------+
|   Budi Santoso |
+----------------+

Loops are not allowed yet — write the lines one by one.

Problem 3 — Table with tabs

Open exercises/02/homework/03-tabel-tab.cpp. Print a three-row table containing the names and scores of three friends, separated by \t so the columns line up.

Problem 4 — Fix the errors

Open exercises/02/homework/04-perbaiki-error.cpp. This file is deliberately made to fail to compile and contains three mistakes. Compile, read the first message, fix one mistake, compile again — until the program runs and prints Semua error sudah diperbaiki.

Challenge — Nested quotes

Open exercises/02/homework/05-kutipan.cpp. Print exactly the following line, including the quotes and backslash:

Guru berkata: "tulis \n untuk pindah baris"

OSN-style exercises

The following three problems are written in the format used in OSN: description, input format, output format, constraints, then examples. None of them uses input yet — reading input is only covered in Chapter 03 — but the way to work on them is exactly the same as a real problem: write it in one .cpp file, run it, then compare its output with the example until it is identical character by character.

The skeletons for all three are in exercises/02/osn/.

Problem 1 — Chessboard

The OSN committee prints an 8 × 8 chessboard for a between-rounds game. Black squares are drawn as # and white squares as .. The square in the top-left corner is black, and the square colors alternate both to the right and downward.

Input format. No input.

Output format. Eight lines, each containing eight characters # or ..

Constraints. The board size is fixed at 8 × 8. Loops are not allowed yet.

Sample output

#.#.#.#.
.#.#.#.#
#.#.#.#.
.#.#.#.#
#.#.#.#.
.#.#.#.#
#.#.#.#.
.#.#.#.#

Explanation. There are only two row shapes, and they alternate. Writing eight cout lines is enough; what is tested here is carefulness, not technique.

The skeleton: exercises/02/osn/01-papan-catur.cpp

Problem 2 — Staircase

Draw a right-aligned staircase with five steps. The first line contains one #, the second line two #, and so on until the fifth line contains five #. Each line is exactly five columns wide, so the # signs always end at the fifth column.

Input format. No input.

Output format. Five lines. Line i contains 5 - i spaces followed by i # signs. There must be no extra spaces at the end of a line.

Constraints. The staircase height is fixed at 5.

Sample output

    #
   ##
  ###
 ####
#####

Explanation. The first line contains four spaces then one #, so its length is five characters. Note the ban on trailing spaces: a right-aligned staircase does not need them, but a left-aligned staircase that is "tidied up" with spaces at the end will be rejected.

The skeleton: exercises/02/osn/02-tangga.cpp

Problem 3 — Shop Receipt

A cashier prints a receipt containing the shop name, the location of its log file, and two item lines. The shop name is enclosed in double quotes, and the file location is written with Windows-style folder separators. Columns are separated by one tab character.

Input format. No input.

Output format. Four lines:

  1. the word Toko, a tab, then "Sumber Rejeki" including its quotes;
  2. the word Berkas, a tab, then C:\struk\2026.txt;
  3. the word Pensil, a tab, 3, a tab, 6000;
  4. the word Buku, a tab, 2, a tab, 14000.

Constraints. The column separator must be one tab character, not several spaces.

Sample output

Toko    "Sumber Rejeki"
Berkas  C:\struk\2026.txt
Pensil  3   6000
Buku    2   14000

Explanation. A double quote inside text is written \", a single backslash is written \\, and a tab is written \t. On screen, a tab looks like several spaces — but to the judging machine the two are different, and replacing a tab with spaces will be judged wrong.

The skeleton: exercises/02/osn/03-struk.cpp

Stuck or already done? Open the homework solutions page.