• Part One


    Every computer application (program) must have a starting point. If I hand a book to you and ask you to start reading it, you will undoubtedly skip past the title page and table of contents and go right to Chapter 1 and start reading. In the same way when an operating system like Windows 7 is asked by the user to launch an application, Windows 7 will look for the equivalent of "Chapter 1" in the program - this part of the program is the function named "main". Every C++ program must have a function named "main". So that is where we will start learning about functions.

    The C++ program below defines a function named "main" that simply prints a greeting to the user's screen and then stops.

    Select this program text and paste it into the text box available at http://codepad.org (make sure you select the language to be C++) and then hit the Submit button.

    #include "iostream"
    using namespace std;

    int main()
    {
       cout << "Hello computer programmer!";
    }

    This program will print the following to the screen:

    Hello computer programmer!

    Here is a description of the program code line-by-line.

    The first two lines of this program are used to include some predefined code that allows you to print output to the screen.

    The third line starts defining exactly what the function named "main" is supposed to do. Ignore the "int" and the open- and close-parenthesis for now - just focus on the name of the function which is main. 

    The fourth line (the open-curly-brace) marks the beginning of the list of things that our function is going to perform while the sixth line (the close-curly-brace) marks the end of that list.

    The fifth line is the actual work that our function "main" is going to do - it means take the sentence "Hello computer programmer!" and push it to the console output (i.e. the screen).

    Let's enhance our program to do some math for us. Cut-and-paste this into codepad and hit the Submit button:

    #include "iostream"
    using namespace std;

    int main()
    {
       cout << "Hello computer programmer!" << endl;

       cout << "2 + 2 = " << 2 + 2 << endl;
    }

    The program output should look like this:

    Hello computer programmer!

    2 + 2 = 4

    We modified the code to print an end-of-line (endl) so that each line of text appears on a new line. And we added the calculation 2+2.