An introduction to writing C++ programs


Keywords and identifiers

words in C++ programs fall into five categories:

Syntax rules


C++ program parts

For the moment, we will consider five main parts for a C++ program:
  1. Pre-processor directives: these give the compiler information about how to translate the source code (e.g. which libraries to include)
  2. Constant definitions: which fixed values are used by the program (e.g. 1.196 in the metres-to-yards conversion)
  3. Main program heading: indicates the start of the instructions to be executed
  4. Main program declaration section: where the programmer defines variables (data storage spaces) to be used in the main program
  5. Main program statement section: the actual instructions to be executed

Program parts (expanded)

  1. Pre-processor directives:
  2. Constant definitions:
  3. Main body heading:
    int main() {
    
  4. Main body - declaration of variables
  5. Main body - statements section

    Return a status value to the shell that controls user programs (0 is the default "everything is ok" status value):

       return 0;
    

    Finally, indicate the end of the main program section by matching main's opening bracket with a closing bracket:

     }
    

    A small example: Hello World

    If compiled and run, the output would look like:
    Hello World!
    
    Some notes on the Hello World code above:

    Programming style: start good habits early!

    Examples of the effect of style:

    The two programs below take the radius of a circle, and calculate its area and diameter.

    They are functionally identical, but one would clearly be much easier to understand and modify than the other.

    POOR STYLE IS POOR PROGRAMMING - IT CAUSES ERRORS AND COSTS TIME AND RESOURCES IN THE REAL WORLD

    Poor use of whitespace

    Better use of whitespace


    Another example: our metric conversion problem

    Design of a solution

    The resulting source code

    #include <cstdio>
    
    using namespace std;
    // Conversion factor
    const float MetresToYards = 1.196;
    
    int main()
    {
       float SqMetres;  // input value
       float SqYards;   // converted value
    
       // Prompt and read input
       printf("Enter the fabric size in sq. metres\n");
       scanf("%f", &SqMetres);
    
       // Apply conversion factor
       SqYards = MetresToYards * SqMetres;
    
       // Display results
       printf("%f square metres equals %f square yards\n", SqMetres, SqYards);
    
       // finished
       return 0;
    }