Entering Programs

Wednesday, 10 July 2013

Entering the Program


The programs shown in this book are available from Osborne’s Web site: www.osborne.com. However, if you want to enter the programs by hand, you are free to do so. Typing in the programs yourself often helps you remember the key concepts. If you choose to enter a program by hand, you must use a text editor not a word processor. Word processors typically store format information along with text. The problem is that this format information will confuse the C++ compiler. If you are using a Windows platform, then you can use WordPad, or any other programming editor that you like. The name of the file that holds the source code for the program is technically arbitrary. However, C++ programs are normally contained in files that use the file extension cpp. Thus, you can call a C++ program file by any name, but it should use the. Cpp extension. For this example, call the source file MyProg.cpp so that you can follow along. For most of the other programs in this book, simply use a name of your own choosing.



Compiling the Program

How you will compile MyProg.cpp depends upon your compiler, and what options you are using. Furthermore, many compilers, such as Microsoft’s Visual C++ and Borland’s C++ Builder, provide two different ways for compiling a program: the command line compiler and the Integrated Development Environment (IDE). Thus, it is not possible to give generalized instructions for compiling a C++ program that will work for all compilers. You must consult your compiler’s instructions. The preceding paragraph not with standing, two of the most popular compilers is Visual C++ and C++ Builder. For the benefit of readers using one of these compilers, brief compilation instructions are provided here. For both Visual C++ or C++ Builder, the easiest way to compile and run the programs in this book is to the use the command-line compilers offered by these environments, and that is the method described.
To compile MyProg.cpp using Visual C++, you will use this command line.
C:\...>cl -GX MyProg.cpp
The –GX option enhances compilation. To use the Visual C++ command-line compiler, you must first execute the batch file VCVARS32.BAT, which is provided by Visual C++. (You will want to consult your Visual C++ documentation for details.) To compile MyProg.cpp using C++ Builder, use this command line.
C:\...>bcc32 Sample.cpp
The output from a C++ compiler is executable object code. For a Windows environment, the executable file will use the same name as the source file, but have the .exe extension. Thus, the executable version of MyProg.cpp will be in MyProg.exe.
NOTE:
If you are receiving error messages when you try to compile the first sample program and are positive that you have entered it correctly, then you may be using an older C++ compiler that predates the ANSI/ISO standard for C++. If this is the case, refer to Appendix B for instructions on using an older compiler.





Run the Program


After a C++ program has been compiled, it is ready to be run. Since the output from a C++ compiler is executable object code, to run the program, simply enter its name at the command prompt. For example, to run MyProg.exe uses this command line:
C:\...> My Prog
When run, the program displays the following output.
This is my first C++ program.
If you are using an Integrated Development Environment, then you can run a program by selecting Run from a menu. Consult the instructions for your specific compiler. As mentioned earlier, for the programs in this book, it is usually easier to compile and run from the command line.
One last point: The programs in this book are console-based, not window-based. That is, they run in a Command Prompt session. C++ is completely at home with Windows programming. Indeed, it is the most commonly used language for Windows development. However, none of the programs in this book use the Windows Graphic User Interface (GUI). The reason for this is easy to understand: Windows is a complicated environment to write programs for, involving many side issues unrelated to the C++ language. In contrast, console-based programs are much shorter and are the type of programs normally used to teach programming. Once you have mastered C++, you will be able to apply your knowledge to Windows programming with no trouble.

A Line-by-Line Explanation


Now that you have successfully compiled and run the first sample program it is time to understand how it works. Towards this end, we will examine the program line by line. The program begins with the lines.
/* Program #1 - A first C++ program.
Enter this program, then compile and run it.
*/
This is a comment. Like most other programming languages, C++ lets you enter a remark into a program’s source code. The contents of a comment are ignored by the compiler. The purpose of a comment is to describe or explain the operation of a program to anyone reading its source code. In the case of this comment, it identifies the program. In more complex programs, you will use comments to help explain what each feature of the program is for and how it goes about doing its work. In other words, you can use comments to provide a “play-by-play” description of what your program does. In C++, there are two types of comments. The one you’ve just seen is called a multiline comment. This type of comment begins with a /* (a slash followed by an asterisk). It ends only when a */ is encountered. Anything between these two comment symbols. I completely ignored by the compiler. Multiline comments may be one or more lines long. The second type of comment is found a little further on in the program; we’ll be discussing it shortly. The next line of code looks like this:
#include <iostream>
The C++ language defines several headers, which contain information that is either necessary or useful to your program. For this program, the header <iostream> is needed. (It is used to support the C++ I/O system.) This header is provided with your compiler. A header is included in your program by using the #include directive. Later in this book, you will learn more about headers and why they are important. The next line in the program is using namespace std; This tells the compiler to use the std namespace. Namespaces are a relatively recent addition to C++. Although namespaces are discussed in detail later in this book, here is a brief description. A namespace creates a declarative region in which various program elements can be placed. Elements declared in one namespace are separate from elements declared in another. Namespaces help in the organization of large programs.
The using statement informs the compiler that you want to use the std namespace. This is the namespace in which the entire Standard C++ library is declared. By using the std namespace, you simplify access to the standard library. The next line in the program is // main () is where program execution begins. This line shows you the second type of comment available in C++: the single-line comment. Single-line comments begin with // and stop at the end of the line. Typically, C++ programmers use multiline comments when writing larger, more detailed commentaries and they use single-line comments when short remarks are needed. However, this is a matter of personal style. The next line, as the preceding comment indicates, is where program execution begins: int main () All C++ programs are composed of one or more functions. (Loosely speaking, a function is a subroutine.)
Every C++ function must have a name, and the only function that any C++ program must include is the one shown here, called main ( ). The main ( ) function is where program execution begins and (most commonly) ends. (Technically speaking, a C++ program begins with a call to main ( ) and, in most cases, ends when main( ) returns.) The opening curly brace on the line that follows main ( ) marks the start of the main( ) function’s code. The int that precedes main ( ) specifies the type of data returned by main( ). As you will learn, C++ supports several built-in data types and int is one of them. It stands for integer.
The next line in the program is cout << "This is my first C++ program.";
This is a console output statement. It causes the message this is my first C++ program. to be displayed on the screen. It accomplishes this by using the output operator <<. The << operator causes whatever expression is on its right side to be output to the device specified on its left side. cout is a predefined identifier that stands for console output, which (most generally) refers to the computer’s screen. Thus, this statement causes the message to be output to the screen. Notice that this statement ends with a semicolon. In fact, all C++ statements end with a semicolon.
`The message "This is my first C++ program." is a string. In C++, a string is a sequence of characters enclosed between double quotes. As you will see, strings are used frequently in C++. The next line in the program is return 0; This line terminates main ( ) and causes it to return the value 0 to the calling process (which is typically the operating system). For most operating systems, a return value of 0 signifies that the program is terminating normally. Other values indicate that the program is terminating because of some error. Return is one of C++’s keywords, and it is used to return a value from a function. All of your programs should return 0 when they terminate normally (that is, without error). The closing curly brace at the end of the program formally concludes the program. Although the brace is not actually part of the object code of the program, conceptually you can think of a C++ program ending when the closing curly brace of main ( ) is executed. In fact, if the return statement were not part of this sample program, the program would automatically end when the closing curly brace was encountered.

Handling Syntax Errors


As you may know from your previous programming experience, it is quite easy to accidentally type something incorrectly when entering code into your computer. Fortunately, if you enter something incorrectly into your program, the compiler will report a syntax error message when it tries to compile it. Most C++ compilers attempt to make sense out of your source code no matter what you have written. For this reason, the error that is reported may not always reflect the actual cause of the problem. In the preceding program, for example, an accidental omission of the opening curly brace after main ( ) will cause some compilers to report the cout statement as the source of a syntax error. Therefore, when you receive a syntax error message, be prepared to look at the two or three lines of code that precede the point at which the error is flagged.
Many C++ compilers report not only actual errors, but also warnings. The C++ language was designed to be very forgiving, and to allow virtually anything that is syntactically correct to be compiled. However, some things, even though syntactically correct, are suspicious. When the compiler encounters one of these situations, it prints a warning. You, as the programmer, then decide whether its suspicions are justified. Frankly, some compilers are a bit too helpful and flag warnings on perfectly correct C++ statements. There are also compilers that allow you to turn on various options that report information about your program that you might like to know. Sometimes this information is reported in the form of a warning message even though there is nothing to be "warned" about. The programs in this book are in compliance with Standard C++, and when entered correctly, they will not generate any troublesome warning messages.
Most C++ compilers offer several levels of error (and warning) reporting. Generally, you can select the specific type of error reporting that you want. For example, most compilers offer options that report such things as inefficient constructs or the use of obsolete features. For the examples in this book, you will want to use your compiler's default (or "normal") error reporting. However, you should examine your compiler's documentation to see what options you have at your disposal. Many compilers have sophisticated features that can help you spot subtle errors before they become big problems. Understanding your compiler's error reporting system is worth the time and effort that you spend.

Sample example

Perhaps no other construct is as important to a programming language as the assignment of a value to a variable. A variable is a named memory location that may be assigned a value. Further, the value of a variable can be changed one or more times during the execution of a program. That is, the content of a variable is changeable, not fixed. The following program creates a variable called x, gives it the value 1023, and then displays the message This program prints the value of x: 1023 on the screen.
// Program #2 - Using a variable
#include <iostream>
Using namespace std;
int main ()
{
int x; // this declares a variable
x = 1023; // this assigns 1023 to x
Cout << "This program prints the value of x: ";
Cout << x; // This displays 1023
Return 0;
}

This program introduces two new concepts. First, the statement int x; // this declares a variable declares a variable called x of type integer. In C++, all variables must be declared before they are used. Further, the type of values that the variable can hold must also be specified. This is called the type of the variable. In this case, x may hold integer values. These are whole-number values whose range will be at least –32,768 to 32,767. In C++, to declare a variable to be of type integer, precede its name with the keyword int. Later, you will see that C++ supports a wide variety of built-in variable types. (You can create your own data types, too.) The second new feature is found in the next line of code: x = 1023; // this assigns 1023 to x As the comment suggests, this assigns the value 1023 to x. In C++, the assignment operator is the single equal sign. It copies the value on its right side into the variable
on its left. After the assignment, the variable x will contain the number 1023. The two cout statements display the output generated by the program. Notice how the following statement is used to display the value of x: cout << x; // This displays 1023 In general, if you want to display the value of a variable, simply put it on the right side of << in a cout statement. In this specific case, because x contains the number 1023, it is this number that is displayed on the screen. Before moving on, you might want to try giving x other values and watching the results.

A More Practical Example

Your first two sample programs, while illustrating several important features of the C++ language, are not very useful. The next sample program actually performs a meaningful task: It converts gallons to liters. It also shows how to input information.
// This program converts gallons to liters.
#include <iostream>
using namespace std;
int main()
{
int gallons, liters;
cout << "Enter number of gallons: ";
cin >> gallons; // this inputs from the user
liters = gallons * 4; // convert to liters
cout << "Liters: " << liters;
return 0;
}
This program first displays a prompting message on the screen, and then waits for you to enter a whole number amount of gallons. (Remember, integer types cannot have fractional components.) The program then displays the approximate liter equivalent. There are actually 3.7854 liters in a gallon, but since integers are used in this example, the conversion is rounded to 4 liters per gallon. For example, if you enter 1 gallon, the program responds with the metric equivalent of 4 liters. The first new thing you see in this program is that two variables, gallons and liters, are declared following the int keyword, in the form of a comma-separated list. In general, you can declare any number of variables of the same type by separating them commas. (As an alternative, the program could have used multiple int statements to accomplish the same thing.)
The function uses this statement to actually input a value entered by the user: cin >> gallons; // this inputs from the user cin is another predefined identifier that is provided with your C++ compiler. Cin stands for console input (which generally means input from the keyboard). The input operator is the >> symbol. The value entered by the user (which must be an integer, in this case) is put into the variable that is on the right side of the >> (in this case,
gallons). There is one more new thing in this program. Examine this line:
cout << "Liters: " << liters; It uses two output operators within the same output statement. Specifically, it outputs the string "Liters: " followed by the value of liters. In general, you can chain together as many output operations as you like within one output statement. Just use a separate << for each item.

No comments:

Post a Comment