C++ Notes: Program Structure

Using Borland/Inprise C++Builder 4/5

We're going to use JBuilder to build a console based program, not a GUI (Graphical User Interface) program. We won't be using the default form windows that appear when you first run C++Builder.
  1. Start C++Builder.
  2. Ignore the windows that C++Builder starts with.
  3. Select the "File/New..." menu item.
  4. Choose "Console Wizard" from the window that appears.
  5. The dialog box varies, depending on the version, but you will select "Console" or "Console Application", "Execution Type" (".EXE" should be selected), and you should not include VCL. Click "Finish".
  6. You will see a sample starting C++ main console program. Ignore it and replace it with your program.
  7. Compile and Run your program the the "Run/Run" menu item or F9.
  8. Stepping thru your program can be done with F8 (menu item "Run/Step Over").
  9. You can stop your program with CTRL-C.
  10. Save your "project" (.bpr, .cpp files) somewhere (Drive D in the lab).
   

Header Files

#include <iostream>Stream I/O. Defines cout and cin streams, and endl, fixed, and showpoint manipulators.
#include <iomanip>More I/O manipulaters: setw(w) and setprecision(p).
#include <fstream>File I/O.
#include <string>Defines the string type and string functions.
#include <cstring>Defines C-style string (array of chars) functions.

General Structure

A common structure for relatively simple C++ programs that are contained in one file is:
General RuleExample
  1. Comments describing program, author, ...
  2. Include statements.
  3. Using statement.
  4. Global declarations (consts, types, variables, ...).
  5. Function headers (declarations).
  6. Main function body.
  7. Function bodies.
Some older compilers may not be in complete compliance with the latest C++ standard. Some features that are commonly lacking and how to solve the problem are:
StandardPre-Standard
#include <xxx>You may have to add a ".h" to the name of a header file. Eg, "#include <iostream.h>" instead of the standard "#include <iostream>".
#include <string>This header file and the string type may not be defined. Use the older C-style strings and the functions in <cstring.h>, or find a definition for the string type and functions.
using namespace std;Namespaces are not in older versions of C++. Omit this statement.
boolbool type is not in some older versions of C++. Use int, 1 as true, 0 as false.
//--- Print Ulam Sequence....
#include <iostream>

using namespace std;

int main() {
   int n;   // Ulam sequence start
   while (cin >> n) {
      cout << "n = " << n << endl;
      while (n > 1) {
         if (n%2 == 0) {  // if even
            n = n /2;
         }else{           // if odd
            n = 3*n + 1;
         }
         cout << "n = " << n << endl;
      }
   }
   return 0;
}
E-mail comments to Fred Swartz (fred@leepoint.net)