First | Next | Previous | Last | Glossary | About

# Introduction to programming with C++

- A first C++ program
- Simple program structure
- Output from a C++ program
- Tutorial - The Programming Process

## A first C++ program

This first session gives you an overview of the C++ program and the programming activity, ie writing program source and building it into a executable program.

Initially you will know very little about what is taking place but don't be alarmed - in the weeks to come you will learn more about all of the topics introduced here.

    #include <iostream.h>

    /* Sample 1 - Hello  */
    /* This is a comment */

    int main()  /* Every program has a main function */
                /* It is the main entry point of the */
                /* program but need not be the first */
                /* statement.                        */
    {           // The braces indicate the start
     cout << "Hello World" << endl;
     return 0;
                // and finish of a group of statements
    }
    // That was a complete C++ program, most of it
    // was comments. Every statement is terminated by a
    // semi-colon. This is the last line.

We will first look at the basic structure of a C++ program then spend a little time looking at the simple data types. By the end of the session we should have enough information to be able to write simple C++ programs.

- Every C++ program has 1 and only 1 main entry point.
- The program statements associated with a routine are enclosed in braces { }. A statement is an expression terminated by a semi-colon.
- A semi-colon terminates each executable statement.

Comments are enclosed in /* ... */ pairs, or if on a single line a pair of slashes //.

    //ex1.cc
    #include <iostream.h>
    int main()
    {
      cout << "Hello World" << endl;
      return 0;
    }

The program without comments :

Everybody does this as a first C++ program!

Return to top of page

## Simple program structure

The program displays a simple string Hello World and then terminates. We should analyse this simple program because every program follows the same basic pattern.

The include file is a file of function, constant and other declarations which can be used by any source file that needs those declarations. The darts <> indicate that the include file can be found in a default location (the include directory) in the compiler installation. Usually a C++ compiler installation follows a directory structure like this:

Most installations will have other subdirectories but I think all C and C++ systems will reflect at least the simple structure shown in Figure 2. The root directory isn't always called "/usr", although this is often the case on UNIX systems, it may have some name that indicates the compiler brand. Figure 3 shows a typical installation for the popular GCC C/C++ compiler. Here you can see the bin, include and lib directories along with many others stemming from the root directory gcc-2.9.5.

Every program has a main function. This is the starting point for the program, from here you launch all the work the program will do. Every function in C++ has data type, main is typically an integer. This means that when the function finishes execution it can return an integer value to the caller. You will learn more about data types and functions soon.

In C and C++ a block is defined by opening and closing braces { }.

The table shows some more detail of the structure of a C++ program:

Includes and Defines |
    #include <iostream.h>
    #include "myfile.cpp"
    #define MAX 100
| include files which are enclosed in "" (doublequotes) are found in the current directory or the directory indicated inside the quotes.
Describe the functions |
    void func1(void);
    int add(int x,y);
| These are function prototypes.
Global declarations | int maxx, minn; | Since maxx and min are declared outside functions they are visible to everything in the source file.
Main program |
    int main()
    { calls to functions
    }
| main sets the entry point for the program.
Define the functions |
    void func1(void)
    { function  code
    }

    int add(int x,y)
    { function  code
    }
| The function prototypes declared above are defined in detail here.

A note on include files:

    #include <iostream>
    #include <string>

The more recent C++ compilers leave out the h in iostream.h so it is quite usual to see directives like this:

    #include <iostream.h>
    #include <string.h>

rather than the traditional directive:

Return to top of page

## Output from a C++ program
The stream cout and the output operator <<

The combination of cout and << is a standard and simple way of producing output from a program.

    // ex2.cc - output
    #include <iostream>

    int main()
    {
     int sum;   /* Declare a variable of type integer  */
                /* The variable is declared within the */
                /* main function                       */

     cout << "Program \n";
     cout << "Test 2 \n.1\n..2\n...3\n";
     sum = 120 + 34;
     cout << "The sum of 120 and 34 is " << sum << endl;

    /* The \n is the newline character. We can use a variety
       of control chars
    */
    }

- Every variable to be used in a C++ program must be declared before it is used.
- The stream cout can uses the output operator <<. This operator << manages the task of sending values to the stream called cout. A stream can be understood as a file.
- The \ character in the cout statement indicates an output control character, e.g. \n - newline, \t - tab. There is a section later in these notes that looks at the escape sequences.

In this line:

    cout << "The sum of 120 and 34 is " << sum << endl;

I used the end line manipulator endl. This causes an end of line to be written to cout and has much the same effect as using \n.

    #include <iostream>

    int main()
    { int sum;
      cout << "Program \n";
      cout << "Test 2 \n.1\n..2\n...3\n";
      sum = 120 + 34;
      cout << "The sum of 120 and 34 is " << sum << endl;
      return 0;
    }

Here is the program less comments:

In the main() function of many of the sample programs you will see the statement return 0; or something similar. Although it isn't mandatory I suggest you use too.

Return to top of page

## Tutorial - The Programming Process

This is just an introductory session and it's main purpose is to introduce you to process of editing source programs and generating executable programs. Don't be too concerned about objects in the program which you haven't met before most of them won't have any real meaning. Over the next few weeks you will use a large part of the C++ language.

Creating and compiling a C++ program - Linux

1. Use vi or pico or some editor to create the source program |
    vi ex1.cc
    OR
    pico -d ex1.cc
2. Run the compiler to compile and link the program |
    g++ -o ex1 ex1.cc
3. Run the program |
    ./ex1

The compiler has many command line switches and the simplest form of the command line is g++ ex1.c which takes the source file ex1.cc and creates a file called a.out which is the executable program. Step 2 shows how to give the executable program some other name.

Creating and compiling a C++ program - DOS/Windows 95/98

If you don't have a Linux system or you would rather work in Windows then you can if you have installed gcc and the programmers file editor. All of the programs you work with can also be created in the DOS/Windows 95/98 environment.

To see how to use this environment refer to the document PFE_GUIDE.DOC or the guide to PFE. You may also want to read the PFE configuration guide.

Setting up your directory structure

It is quite likely that you will be working in two environments:

- Linux
- Windows 95

and in each case you should set up a directory structure which will aid you in your work.

I strongly recommend that your structure be:

If you use this directory structure on both your Linux and W95 environments then you can easily transport programs between the two environments.

Now create and compile the programs shown below. The primary object of the following exercises is just to give you some practice in using the programming environment and doing the programming process.

    //ex1.cc
    int main()
    { cout << "Hello World!" << endl;
      return 0;
    }

1. You just have to do this program, it is part of the C and C++ initiation ceremony.

    //ex2.cc
    int main()
    {
    int x = 0,y = 2,z = 1025;
    float a = 0.0,b = 3.14159,c = -37.234;

      x = x + 1;  /* This increments x */
      x++;        /* This increments x */
      ++x;        /* This increments x */
      z = y++;    /* z = 2, y = 3 */
      z = ++y;    /* z = 4, y = 4 */

      y = y - 1;  /* This decrements y */
      y--;        /* This decrements y */
      --y;        /* This decrements y */
      y = 3;
      z = y--;    /* z = 3, y = 2 */
      z = --y;    /* z = 1, y = 1 */

      a = a + 12; /* This adds 12 to a */
      a += 12;    /* This adds 12 more to a */
      a *= 3.2;   /* This multiplies a by 3.2 */
      a -= b;     /* This subtracts b from a */
      a /= 10.0;  /* This divides a by 10.0 */

      return 0;
    }

2. This example shows the context in which we use a variety of operators. At this early stage of learning about C++ you can't possibly remember all of the operators but it helps to get a bit of practice just getting used to the syntax of C++.

    //ex3.cc
    #include <iostream>

    int main()
    { int a,b = 32765, c = 1;

      cout << "b = " << hex << b << endl;
      cout << "c = " << hex << c << endl;
      for (a = 15; a > 0; a--)
       { b = b + 1;
         c = c + 1;
         cout << " b = " << oct << b
              << " c = " << hex << c
              << " b + c " << hex << (b + c) << endl;
       }
      return 0;
    }

3. Normally when your program outputs numeric values the values are displayed in decimal but you can display numbers in other number bases.

This example uses a couple of manipulators hex and oct to change the format of output.

You will see the for loop in this and the next example - again don't be concerned about the new elements, just get some practice seeing the syntax and compiling and running the programs.

First | Next | Previous | Last | Glossary | About

Copyright © 1999 - 2001 David Beech