Program Structure


Every C++ program follows this basic/general structure:


int main ()





The following is an example program using the above structure:

/* This program calculates the product of two numbers */

// Compiler Directives

#include <iostream.h>

int main () {

// Local Variable Declaration





cout << "Welcome to the Product Machine\n\n"; // Displays program title

cout << "Please enter the first number: "; // Prompts for first number

cin >> firstNumber; // Grabs first number

cout << "Please enter the second number: "; // Prompts for second number

cin >> secondNumber; // Grabs second number

product = firstNumber * secondNumber; // Calculates product

cout << "The product is " << product << "\n"; // Displays product


· The program begins with a comment box explaining what the program does. A comment is identified either by surrounding it with /* and */ (as in: /* this is a comment */) or by placing // at the beginning of each commented line. In the latter case, all text after // on the same line will be treated as the comment.

· Next is the compiler directive #include <iostream.h>. This statement tells the compiler to include the declarations found in iostream.h, a library which provides the capabilities needed to perform interactive I/O.

· Following this directive is the main C++ function, indicated by

int main () {






· main is the name of the main C++ function. It is the first function run when a program is executed.

· the () after the function name represents the parameter types that will be accepted. If it is empty, or contains the keyword void, it does not accept anything.

· the column of dots represents the body of the program

· The body usually consists of a variable declaration area and the accompanying code. In the above example, we declared three int (integer) variables; namely, firstNumber, secondNumber, and product. Other more commonly used variables types are: double, float, and char.

· The cin/cout functions are interactive input-output (I/O) functions associated with the stream.h library and are explained further in the cin/cout tutorial page.

· Assignments to variables take the form of targetVar = Value; where targetVar must be of a matching type with Value (see tutorial on variable assignment).