Tie koodariksi

C++ Programming

Chapter 2: Program Structure

Many things work the same way in C++ as they do in many other programming languages. The following program gives an example of the structure of a C++ program:
#include <iostream>

using namespace std;

int main() {
    cout << "How many lines? ";
    int n;
    cin >> n;
    // printing staircase
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= i; j++) {
            cout << "*";
        }
        cout << "\n";
    }
}
The program reads the number of rows from the user into variable n and then prints a staircase with n layers. The program execution may look like this:
How many lines? 5
*
**
***
****
*****

Main function

C++ always has the main function main, where the execution of the program begins. In the first chapters of this course, our overall program framework is as follows:
#include <iostream>

using namespace std;

int main() {
    ...
}
In ... is the code you want to execute, and the lines around it are always the same. Later in the course, we will learn the meaning of the lines around it.

Input and output

We can read user input into variables via the cin object. For example, the following code reads the user input to variable x:
int x;
cin >> x;
Similarly, we can print text to the screen via the cout object. Whenever we want a line break in the text, we do this by using the \n tag (newline). The following code is an illustration:
cout << "first ";
cout << "line\n";
cout << "second line\n";
The output of this code is as follows:
first line
second line

Commenting

In C++, there are two ways to add comments to code: A single line comment begins with // and continues to the end of the line. A multi-line comment begins with /* and ends with */.

The following code shows an example of each of these commenting methods:

// this comment is on one line

/* this comment is on
                        two lines */

Terminology

A statement is a single program command. In C++, a semicolon ; indicates the end of a statement.

An expression is part of the code that has a value. For example, x and a + 2 * b are expressions.

A block consists of one or more statements, which are written between { and }. A block is used to indicate, for example, which statements are inside a function, if structure, or loop.

Code formatting

Usual practice is to write each sentence on its own line and indents the code inside the block. However, this is not mandatory as the C++ compiler ignores white space in the code.

For example, the following code snippets work in exactly the same way:

for (int j = 1; j <= i; j++) {
    cout << "*";
}
    for
(int j = 1;
    j <= i;
        j++) { cout << "*"; }
However, the latter code is difficult to read because it differs from the usual practice.

Datatähti 2027 – peruskoulun ja lukion ohjelmointikilpailu käynnissä 26.10.–8.11.2026