It’s traditional in programming for the first code to be entered to output the words ‘Hello, World!’ to the screen. Interestingly, this dates back to 1968 using a language called BCPL.
Step 1 – As mentioned, we’re using Windows 10 and the latest version of Code::Blocks for the rest of the C++ code in this book. Begin by launching Code::Blocks. When open, click on File > New > Empty File or press Ctrl+Shift+N on the keyboard.
Step 2 – Now you can see a blank screen, with the tab labelled *Untitled1, and the number one in the top left of the main Code::Blocks window. Begin by clicking in the main window, so the cursor is next to the number one, and entering:
Step 3 – At the moment it doesn’t look like much, and it makes even less sense, but we’ll get to that in due course. Now click on File > Save File As. Create or find a suitable location on your hard drive and in the File Name box, call it helloworld.cpp. Click the Save as type box and select C/C++ files. Click the Save button.
Step 4 – You can see that Code::Blocks has now changed the colour coding, recognising that the file is now C++ code. This means that code can be auto-selected from the Code::Blocks repository. Delete the #include <iostream> line and re-enter it. You can see the auto-select boxes appearing.
Step 5 – Auto-selection of commands is extremely handy and cuts out potential mistyping. Press Return to get to line 3, then enter:
Note: there’s no space between the brackets.
Step 6 – On the next line below int main(), enter a curly bracket:
This can be done by pressing Shift and the key to the right of P on an English UK keyboard layout.
Step 7 – Notice that Code::Blocks has automatically created a corresponding closing curly bracket a couple of lines below, linking the pair, as well as a slight indent. This is due to the structure of C++ and it’s where the meat of the code is entered. Now enter:
//My first C++ program
Step 8 – Note again the colour coding change. Press Return at the end of the previous step’s line, and then enter:
std::cout << “Hello, world!\n”;
Step 9 – Just as before, Code::Blocks auto-completes the code you’re entering, including placing a closing speech mark as soon as you enter the first. Don’t forget the semicolon at the end of the line; this is one of the most important elements to a C++ program and we’ll tell you why in the next section. For now, move the cursor down to the closing curly bracket and press Return.
Step 10 – That’s all you need to do for the moment. It may not look terribly amazing but C++ is best absorbed in small chunks. Don’t execute the code at the moment as you need to look at how a C++ program is structured first; then you can build and run the code. For now, click on Save, the single floppy disc icon.