Our First Program --- Hello World Program
In this section we will write our first program.
Here is a simple C++ program that prints Hello World to the screen:
Let's break down this code.
What does "compile" mean?
Unlike some other languages, C++ programs cannot be run directly. They first need to be compiled — that is, translated from human-readable text into instructions that the computer understands. This is done by a special program called a compiler. The result of compilation is an executable file (for example, main.exe on Windows or ./main on Linux/Mac).
Including a library
The first line #include <iostream> tells the compiler to include the iostream library, which contains functions for input and output. This is necessary to use the cout command to print text.
The using namespace std instruction
The line using namespace std; means that we are using the std namespace. The std namespace contains standard objects and functions, including cout and endl.
The main function
The main part of the program lives inside the main() function. The main() function is the entry point of the program — this is where execution begins when the program is launched.
Printing text
The line cout << "Hello World" << "\n"; is used to print text to the screen. cout stands for "console output". We use the << operator to send text to cout.
At the end we have << "\n" — this is a newline character that moves the cursor to the next line.
"\n"orendl? Both move to a new line. We use"\n"— it is more common and slightly more efficient. You will also encounterendlin other materials; just know that they do almost the same thing.
The semicolon
Notice the semicolon (;) at the end of each line. It marks the end of a statement and tells the compiler that one command has finished. Without semicolons the code will not compile.
Returning a value
The main() function ends with return 0;. The value 0 means the program finished successfully. If a program ends with a non-zero value (return 1; and so on), it signals that an error occurred.