First Program

The first program to learn the C++ syntax is a simple program which print Hello World to screen.

Open in the command line (terminal) with a simple editior like emacs a new file called helloworld.cpp.

emacs helloworld.cpp

or

vi helloworld.cpp

Program: Hello World
1#include <iostream>
2
3int main() {
4    
5    std::cout << "Hello world!" << std::endl;
6    
7    return 0;
8}

Key in this code and save it and then can you quit your first program. Now we try to compile with:

g++ -o helloworld helloworld.cpp

If you have a correct syntax without errors then you can run with:

./helloworld

Should appear some warnings without error messages when you compiling then you can ignore it. Now I will not repeat how to use the compiler or an editor or how to start your build program.

Program Hello World in detail
Line 1:
We include the standard library for input and output streams in line one with #include <iostream>. In C should we call #include <stdio.h> but C++ has its own libraries without .h endings but you can use C libraries too with #include <stdio.h> or #include <cstdio>.
Line 3:
In line three we define the main function with int main() {. The command int is a datatype acronym and is an integer datatype, but the main function can define with void too. The advantage for an integer definition is that you can return a control value to terminal or command line. The bracket { define the begin of a function and } define its end.
Line 5:
The output command for terminal is cout, in standard library is cout defined in a namespace called std and we calling it with std::cout or defining this namespace after the include of library like using namespace std; and than we can call cout without std::. The << chars define an output stream and what you want to print to terminal in a datatype defined in a variable or a string in stands between two " like "Hello world" or in datatype defined variable. The second chars << define a appended command for a string, variable or cout command like endl. The command endl means end line and the effect is a break line.
Line 7:
The command return 0; send a 0 value to terminal or command line that means that your program works successful.
Line 8:
The bracket } shows the end of the main function or generally of a function, loop, scope or an if else clause to example.