Programming in C++ is similar to programming in C#, however there are some differences as to how these programming languages expect you to write your source files.
Program 1 shows the ubiquitous Hello World! program in C++.
Program 1. Hello World!
#include <iostream> using namespace std; int main() { cout << "Hello World!" << endl; return 0; } |
If you don't have Dev C++ installed on your computer, follow these instructions.
The first two lines will be explained later, however, the first line does have two features of note:
Next, we see what is termed a function in C++. A function in C++ allows the programmer to define a sequence of statements which define what a processor should do.
The properties of a function are defined by:
This function has exactly two statements. These are described in the following two sections.
The cout stands for console output, or something which is to be printed to the screen. Whenever you see cout followed by any number of:
this indicates that A should be printed to the screen, followed by B, followed by C and finally, followed by D. In this case, two things are printed:
Program 2. Hello World returns...
#include <iostream> using namespace std; int main() { cout << "Hello World!" << endl << endl << "This is..." << "my second..." << endl << "...program." << endl; return 0; } |
The output for this program, when run, is:
Hello World! This is...mysecond... ...program.
One of the strings are highlighted to ensure it stands out. Of course, in reality, everything would be the same.
A few things to note in this code:
The statement
indicates that this function exits (returns) at this point and the value of the function is the integer 0.
As mentioned before, all1 statements which are to be interpreted as instructions to the CPU must appear inside functions. The main function is used to indicate those statements which the CPU is meant to begin executing when the executable program is run.
In Programs 1 and 2, the main function tells the CPU to print some text to the screen and then the main function ends by returning 0. When the main function returns, the executable program exits. Thus, both Programs 1 and 2 would stop executing once they've printed the text to the screen.
1 This should read almost all, however you will not be directly exposed to the special cases in this course.