C++ Notes: Summary: Program Structure

Small programs

A common structure for simple, one file, C++ programs:
  1. Comments describing program, author, ...
  2. Include statements specify the header files for libraries.
  3. Using namespace statement. Typically this is only using namespace std;
  4. Global declarations (consts, types, variables, ...). Avoid global variables if possible.
  5. Function prototypes (declarations).
  6. Main function definition.
  7. Function definitions.

Example of main program

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
 23 
 24 
 25 
 26 
 27 
 28 
 29 
 30 
 31 
 32 
 33 
 34 
 35 
 36 
 37 
// program-structure/ulam.cpp - Read number, print its Ulam sequence.
// Michael Maus, 2004-10-26

//========================================================= includes
#include <iostream>
using namespace std;

//======================================================= prototypes
int nextUlam(int x);


//============================================================= main
int main() {
    int n;   // Ulam sequence start
    cout << "Enter an integer to see its Ulam sequence." << endl;
    while (cin >> n) {
        cout << "Ulam sequence for " << n << " is " << n;
        while (n > 1) {
            n = nextUlam(n);
            cout << " " << n;
        }
	    cout << endl;
    }
    return 0;
}


//========================================================= nextUlam
int nextUlam(int x) {
    int result;
    if (x%2 == 0) {     // if even
        result = x / 2;
    } else {            // if odd
        result = 3*x + 1;
    }
    return result;
}

Larger program structure

A program that defines classes or numerous methods is divided into many source files. To pass common definitions between these files, header files are created which contain declarations.