Writing your first C++ program
Published on 2018-04-07
We live in the 21st century - a period in which much of our activities are, in a direct or indirect way, related to computers and information technology. Every day, the development of computer science causes changes in the way people work, and augments their personal and professional lives.
Computers have the ability to perform a lot of operations in a short period of time. However, this ability is due to the fact that every computer, naturally, understands and can perform only a limited number of instructions (operations). It is the job of software developers to link, order and group these instructions in a way that is useful to people. In particular, these posts are intended for those who want to learn how to develop applications using one of the most popular programming languages in the world: C++.
Before you create your first C++ program, you need to install a software tool on your personal computer that will allow you to write programs, test them, and build them into software applications that your computer can run. These tools are called "Integrated Development Environment" (abbr. IDE). By default, an IDE contains:
- text editor for the source code (a place where you will write your code)
- compiler and/or interpreter
- debugger
There are several popular integrated development environments for writing C++ programs. Currently, the best free IDE for writing simple programs is Code::Blocks. This tool is used by thousands of users - both for writing small programs and for creating serious commercial projects. Code::Blocks is the main IDE used by the International Olympiad in Informatics.
Download Code::Blocks using the following link: codeblocks-17.12mingw-setup.exe. Please note that the link provided above is for Microsoft Windows. If you're using a different operating system, please click here, and find your OS on the downloads page.
Now, install Code::Blocks by simply running the downloaded setup file. Congratulations, you can now create programs by starting Code::Blocks, creating a new project and writing code.
Steps to create your first program
It's time to create a program. By default, the first code written by all new developers is the so-called "hello world" program:
#include <iostream> using namespace std; int main() { cout << "Hello world!" << endl; return 0; }
To run this program on your computer, do the following:
- run Code::Blocks (from the icon on your Desktop, or through the Start button)
- click File, and then New Project
- select Console Application, and click Go
- click Next
- select C++, and then click Next
- enter the project name "HelloWorld" (the remaining fields will be set automatically)
- check if the Compiler field contains the value "GNU GCC Compiler", and click Finish
- on the left side of your screen, open Workspace, then HelloWorld (or whatever name you used for the project), then Sources and open the main.cpp file (by double-clicking on the left mouse button, or by clicking on the right mouse button and selecting "Open main.cpp")
Delete the existing code. Then, type the code given above (the "hello world" program) in the text editor. Please note the size/case of the letters - C++ distinguishes between uppercase and lowercase letters, so if you type Cout instead of cout, or Main() instead of main(), the program will not work. Make sure that you type the word endl correctly; the last letter in endl is l (lowercase L) and not I (uppercase i) - in many fonts, these two letters look the same. The lines in the program are not preceded by numbers (as in the screen above). The numbers presented there are part of Syntax Highlighter - the tool we use to display the code (so it looks nice). - To run your first program, go to Build (top menu) and then Build and run (or click on F9). If the program does not run, then you made a mistake - check your code line by line. If you can't find the error, look on the bottom side of the Code::Blocks window.
- Bravo. Well done. You have created and executed your first C++ program.
The program given above presents the text "Hello world!" on the computer screen. Although it is very simple, the program contains all key elements of every C++ program. It is actually composed of two major parts:
The first part covers lines 1 and 2. The first line (line 1) tells the compiler that we need tools for reading and writing stuff (input/output stream -> iostream). The system reads the first line (in this case "#include <iostream>"), and replaces it with all the definitions found in the iostream file (stuff for reading and writing). If we wanted to perform complex mathematical operations in the program, we could have asked for tools for executing mathematical functions ("#include <cmath>"), for working with textual data we could have asked for help using strings ("#include <string>"), etc. For now, it is enough to know that in all the programs that we will work with, we will add the line "#include <iostream>" so we can use the keyboard to read input and use the screen to write output.
The second line (line 2) indicates that we will use functions, types and/or constants from the standard namespace (std namespace). If we did not enter the second line, then instead of writing cout we would have needed to write std::cout (because cout is defined in the standard namespace).
The second part of the program is composed of only one function - called main(). In fact, with the exception of the first two lines, the program has the following structure:
int main() { statements; return 0; }
Main function - main()
main() is the first function that is called by the system when executing a C++ program. In the C++ programming language, all functions start with the character '{' and end with the character '}' (these characters can also be used for blocks, which will be discussed later). As a rule, main() ends with a statement to return the result 0 (as a notification to the operating system that the program has finished successfully). Programs that can not complete successfully (for example, they fail to execute a division operation because the denominator is 0) return a value different from zero. All of our programs will contain a main() function. At the end of every main() function we will add the statement "return 0;".
You have certainly noticed that there is an "int" word in the line in which the name of the function is defined. This word actually indicates that the function returns an integer (number) value - the main() function will always be defined like this - i.e. "int main()". You should also notice that there are two brackets "()" after the name "main". These two brackets indicate that main() is actually a function. Optionally, between these brackets, it is possible to define parameters that the function should expect. For example, we may have a function to sum two numbers "int add(int a, int b)".
#include <iostream> using namespace std; int add(int a, int b) { return (a+b); } int main() { cout << "2+5=" << add(2,5) << endl; return 0; }
Functions are really powerful. However, for now, it is enough to understand how to define the main() function, what type of data it returns (int), and what value to return after its execution (0) to indicate that it completed successfully.
The implementation of the hello world program (the program given at the beginning of this post) results in the presentation/printing of the text "Hello world!" on the computer screen. In C++, printing text is done by "inserting" the text (cout << "Hello world!" << endl;) in the default stream "cout". cout denotes the output stream of the current console (the console in which our program is running).
In addition to "Hello world!", we insert a new line character (endl), which is useful if we want to print more lines of text.
It is interesting to note that, due to the use of a symbol to mark the end of a statement (';'), operations can be structured arbitrarily (in different lines) - without changing the result (how the program will work).
Comments
When we write programs, we can also add comments - i.e. parts of the code that are ignored by the compiler. Comments do not have any effect on the program, but they enable us to provide explanations or notes that can be read by another programmer (who would work on the same program).
C++ provides two ways to add comments:
- single-line comments (which start with // and finish at the end of the line in which they are defined)
- multi-line or block comments (start with /*, and end with */).
The following program contains 3 single-line comments and 3 block comments:
//first comment: hello world #include <iostream> using namespace std; /* this is a block comment */ int main( /* no parameters */ ) { cout << "Hello world!" << endl; //prints Hello world! /* block comments can span multiple lines */ return 0; //returns 0 }
Interested in what you saw? You can continue learning from any of these two websites: cplusplus.com or learncpp.com. Both are really good. I will also attempt to provide several tutorials on this blog.