Professional Documents
Culture Documents
Before looking at how to write C++ programs consider the following simple exampl
e program.
//
//
//
//
Sample program
IEA September 1995
Reads values for the length and width of a rectangle
and returns the perimeter and area of the rectangle.
#include <iostream.h>
void main()
{
int length, width;
int perimeter, area;
// declarations
cout << "Length = ";
// prompt user
cin >> length;
// enter length
cout << "Width = ";
// prompt user
cin >> width;
// input width
perimeter = 2*(length+width);
// compute perimeter
area = length*width;
// compute area
cout << endl
<< "Perimeter is " << perimeter;
cout << endl
<< "Area is " << area
<< endl;
// output results
} // end of main program
The following points should be noted in the above program:
Any text from the symbols // until the end of the line is ignored by the compile
r. This facility allows the programmer to insert Comments in the program. Every
program should at least have a comment indicating the programmer's name, when it
was written and what the program actually does. Any program that is not very si
mple should also have further comments indicating the major steps carried out an
d explaining any particularly complex piece of programming. This is essential if
the program has to be amended or corrected at a later date.
The line
#include <iostream.h>
must start in column one. It causes the compiler to include the text of the name
d file (in this case iostream.h) in the program at this point. The file iostream
.h is a system supplied file which has definitions in it which are required if t
he program is going to use stream input or output. All your programs will includ
e this file. This statement is a compiler directive -- that is it gives informat
ion to the compiler but does not cause any executable code to be produced.
The actual program consists of the function main which commences at the line
void main()
All programs must have a function main. Note that the opening brace ({) marks th
e beginning of the body of the function, while the closing brace (}) indicates t
he end of the body of the function. The word void indicates that main does not r
eturn a value. Running the program consists of obeying the statements in the bod
y of the function main.
The body of the function main contains the actual code which is executed by the
computer and is enclosed, as noted above, in braces {}.
Every statement which instructs the computer to do something is terminated by a