In Code::Blocks do the following steps:
1. File Menu -> New -> Empty File
2. Type the source code shown in the screen print below
3. Click on Build and run (circled in red)
4. If there were no syntax errors in your code, the compiler output will tell you there were 0 errors (circled in blue).
The a command prompt will open showing you the output of you program.
5. If you had errors, they will be shown in the compiler output. There will also be a red block marking the line number of the first error. In the screen print below, a semi-colon is missing at the end of line 6. In this case, you will need to fix the error(s) and retry the Build and run.
This section will explain each line of the Hello World program. The following table explains each line of this program. Do not panic if it is not all clear - for most people understanding will come later after lots of practice.
C++ Statement | Explanation |
#include <iostream> | At the top of C++ programs, you will usually find include statements. The C++ programming language is limited, so it is common to include libraries to add additional functionality. In this example, we have included the iostream library which provides us with various input/output commands including the cout and cin functions. |
using namespace std; | The standard library is a collection of functions, constants, and classes that extends the C++ language providing additional functionality. This line says to treat the identifiers (function, constant, class names) in the standard library as though they are part of the main program. This line should be used in almost every program after your include statements. |
int main () | All C++ code is located in containers called functions. All programs will have a function named main which executes first when you run the program. Functions usually return a variable. It is customary to have the main function return an int. |
{ | The open brace begins the function (container) which holds the program. It will always be located immediately after a function header - i.e. main() |
cout << "Hello World!"; | The cout (console out) statement tells the program to output text to the screen. The text to be output is contained within double quotes. Most C++ statements are terminated with a semicolon. |
return 0; | Since the main() function returns an int (integer) variable, the last line in this function should return 0. This means the program exited normally. |
} | The closing brace terminates the main() function. It should match the opening brace. |