CHAPTER 3

Getting Started
with C++

Chapter Objectives

By the end of the chapter, readers will be able to:

images  Understand the case sensitivity and semicolon rules of C++.

images  Understand how whitespace is used to increase readability.

images  Comment source code.

images  Understand the role of main.

images  Use #include statements.

Introduction

Up to this point, everything we have covered has been language independent. Now it is time to write some actual C++ code. This chapter discusses some of the fundamental aspects of C++ programs.

3.1 C++ Basics

One of the first things to understand about C++ is that it is a case-sensitive language. This means the word “cat” is different from the word “Cat”—or any other variations related to capitalization. Not all languages are case sensitive. Visual Basic and Ada are two examples of languages that are case insensitive.

Second, you should be aware that all programming languages are composed of a series of reserved words that have a special or predefined meaning within the language and therefore cannot be used as user-defined identifiers.

Another C++ language requirement is the use of semicolons to end or terminate most statements. If the statement is an instruction, the semicolon must be included. The omission of the semicolon is one of the most common errors we have seen in teaching C++ (and C as well).

Some categories of statements that don't require semicolons are:

images  Preprocessor directives

images  Function headers

images  Control statements

Except for “preprocessor directives,” none of these terms will make much sense yet. Rest assured, however, that throughout the following chapters, the meaning of these terms will become much clearer.

3.2 Whitespace

Whitespace usually refers to empty spaces inserted around related items. In the area of computer science and programming, the term refers to an empty or non-visible character (i.e., a space or tab), including blank lines. We will use whitespace to improve the readability and maintainability of our programs. Example 3.2.1 shows two identically functional and correct programs, the first using an appropriate amount of whitespace and the second using no whitespace other than what is required to make the program compile.

images

Clearly the first example is much more readable, even with just these few lines of code. Imagine how much more difficult it would be to read a program with 100,000 lines of code written using only the minimum required whitespace.

Some beginning programmers are apprehensive about putting whitespace in their code because of the misguided notion that it will increase the size of the executable program. While we appreciate their good-hearted intentions to save disk space and memory, this is not true. Whitespace is ignored by the compiler and therefore removed from the executable, resulting in no difference in file size.

3.3 Comments

Comments are lines of C++ code that are ignored by the compiler. Like whitespace, using comments has no impact on the overall behavior, flow, or size of your program. These lines are used to document the source code for you or for other programmers. Comments aid in the readability and maintainability of your code.

There are two types of comments available for programmers in C++: inline and block. An inline comment starts with a double forward-slash (//) and continues until the end of the line. Example 3.3.1 shows an inline comment. Note that an inline comment can only span one line.

images

The block comment starts with a forward-slash and asterisk combination (/*) and ends with an asterisk and forward-slash (*/). This style of comment is sometimes referred to as a C-style comment. Unlike the inline comment, the block comment can span multiple lines of source code, as demonstrated in Example 3.3.2.

images

Section 3.3 Exercises

For each of the following code fragments, indicate if there are any errors. If there is an error, specify how you would fix it.

 1. \ This is an inline comment

 2. /* This is a comment

 3. /* This is another comment /*

 4. /* Isn't this /* a fun */ comment */

 5. // This is a
    multiline
    comment

3.4 The main Function

When you run a program, how does the computer know where in the program to start? Many beginning programmers incorrectly assume that the first physical line of code in the file executes first. However, a C++ program always starts its execution at the function named main. It doesn't matter if main is physically located at the beginning or end of your source code—its contents will always be the first executed. For this reason, we often see main listed as the first function in a program.

If you were to type the code in Example 3.4.1 into your IDE, some words would be blue. They are reserved words, meaning they already have a predefined purpose in C++.

images

Even though Example 3.4.1 compiles and runs, it doesn't do anything constructive; it is just used to illustrate the overall format of main.

Observe that main is always written in lowercase and that no semicolon is used after the function header. Notice also that parentheses and curly braces always come in pairs. If there is an opening parenthesis or brace, there must be a matching closing parenthesis or brace. The job of the braces is to group statements together and to define the beginning and end of the function body.

There are some issues with main that we have not yet addressed, such as the meaning of the int before main and the return statement. Although at this point the underlying meanings are not important, they will be addressed in more detail in later chapters. For now, just remember that they are necessary for creating a C++ program.

Section 3.4 Exercises

For each of the following code fragments, indicate if there are any errors. If there is an error, specify how you would fix it.

1.  int Main ( )

2.  int main ( );

3.  int main()

images

4.  int main()

images

5.  int main ( )

images

3.5 The #include Preprocessor Directive

The preprocessor directive #include allows the programmer to access external or separate files called header files. These header files contain the information necessary to access many of the predefined C++ routines. While header files are not required to create a valid C++ program, virtually all C++ programs use them because of the powerful constructs to which the header files provide access.

At language translation (compile) time, all of the information for using predefined routines must be provided. Although the implementation of the routines is found in the Standard C++ Library, the header file is required to access these routines.

There are two forms of the #include:

1.  #include <header_file>

2. #include “header_file”

While both of these forms accomplish the same thing, they look for the header file in physically different locations. The first looks for the header file in the include directory, established when the compiler was installed. If the default path was chosen when Visual Studio was installed, you will find the include directory at: C:Program FilesMicrosoft Visual Studio 9.0VCinclude. Header files are just text files, so feel free to open them to see what they contain. However, we strongly suggest you don't change anything in the header file.

The second form looks for the header file in the current directory (the directory where the .cpp file exists) or within the directory specified as a path in the #include statement. This form is generally used to access programmer-created header files. Creating your own header files will be discussed later in this text.

The header file used in most of the programs you will write for this text is <iostream>. Although the full explanation of this file and its associated routines will be left for Chapter 5, we will use it to demonstrate the use of the #include.

In Example 3.5.1 we use the #include to allow us to use the predefined routine cout, which prints or displays text to the screen.

images

3.5.1 Namespaces

In Example 3.5.1, notice the “std::” prefix to the cout statement. This prefix allows access to a named area (namespace) within the Standard C++ Library. As you might expect, having to preface all of the predefined routines with “std::” might become cumbersome after a while. Fortunately, there are a couple of ways of accessing the necessary routines without using the prefix. Example 3.5.2 shows the easiest way to access the needed information.

images

However, the easiest way is not necessarily the best. Another method is shown in Example 3.5.3.

images

Example 3.5.3 doesn't look so difficult, but there is a catch: you have to have a using statement for each routine needed. In some cases, this could quickly create a fairly long list of using statements. In Example 3.5.3 we are bringing into the scope of the program only those specific statements we will be using from the <iostream> header file. By including using namespace std; in Example 3.5.2, we are bringing in many additional routines that may not even be used.

Another thing to keep in mind is that some header files and their associated routines don't require the use of namespaces. An example of such a header file is <cmath>, which allows access to some predefined math routines. These routines are actually a holdover from the C language.

STYLE NOTE Of the three methods available to access routines contained within a namespace, which is the preferred? The answer depends on your organization, which is responsible for dictating the method you should use.

Section 3.5 Exercises

For each of the following code fragments, indicate if there are any errors. If there is an error, specify how you would fix it.

 1. #Include <iostream>

 2. #include “iostream”

 3. #include (iostream)

 4. #include <iostream>;

 5. #include <IOstream>

 6. #include <iostream>

     Using namespace std

 7. using namespace std;

     #include <iostream>

 8. #include <iostream>

     using std:cout;

 9. #include <iostream>

     using std::cout

3.6 Problem Solving Applied

Problem statement: Develop a pseudocode solution to calculate the gross pay for I. M. Sample. Mr. Sample is paid on an hourly basis, does not receive overtime, and is in the 20 percent tax bracket. He has been working for the company for the past six months. Please display his gross pay, the amount of taxes withheld, and his net pay.

Requirement Specification:

Input(s):

Input Type

Data

Source

Decimal

Wage

Keyboard

Decimal

Hours

Keyboard

Output(s):

Output Type

Data

Destination

Decimal

GrossPay

Screen

Decimal

TaxesWithheld

Screen

Decimal

NetPay

Screen

Design:

Required formulas:

images

Pseudocode:

images

Testing and Verification:

Desk Checking:

images

3.7 C—The Differences

Beginning with this chapter, we will provide a unique section for those readers interested in learning some of the fundamental elements associated with the C programming language. The objective of this section is to present and illustrate the C language statements that correspond to the C++ language material presented thus far in the chapter. The focus will clearly be on showing the syntax of the C language. This section is truly optional but provides some additional information for those who need to learn C as well as C++. Although no exercises will be provided in this section, you can use the C++ exercises to practice the C language constructs.

For illustrative purposes, Example 3.7.1 is the C version of the classic “Hello World” program in Example 3.5.1.

images

You are likely to see the word “void” in the parentheses. The word “void” means that main is passed or receives no value or data. It is equivalent to ( ) in C++. Finally, preprocessor directives are very important in C. Like in C++, they basically tell us where we can locate the definitions or meanings of the predefined routines used in our code. The header files would include, however, “.h” extensions, as shown in Example 3.7.1. Notice that namespaces aren't used with C header files.

3.8 SUMMARY

Chapter 3 introduced you to a number of the fundamental components associated with a C++ program. Our discussion started with some C++ basics, including comments, the important role of main, and the use of header files.

As discussed, a couple of different options are available for including comments in your code, such as the /*…*/ and the //. Appropriately commented code, as well as the proper use of whitespace, greatly increases the readability and maintainability of your program.

The function main is required in any C++ program. It is the one function all of our programs will include and the first function to be executed by your program, regardless of its physical location within your code. Obviously, we will have a lot more to say about functions in the following chapters.

Our next topic focused on using header files and provided a brief discussion of name-spaces. We will periodically revisit the topic of namespaces and additional header files in the remainder of the text, as their use becomes warranted.

So now you have seen the full implementation of a complete, albeit very small, C++ program. This overall structure will continue to be expanded and discussed in more detail in the remaining chapters of this text. If you are feeling comfortable with the material presented, you are ready to continue on your C++ journey. If not, please make it a point to review the material presented, firing up your compiler and actually walking through some of the examples. With these fundamental concepts out of the way, it's about to get really exciting!

3.9 Debugging Exercise

Problem: Rewrite your friend's directions in pseudocode form, removing any extraneous information to make them easier to read. Verify that Storm hasn't left anything out and that the directions make sense.

Your friend Storm has invited you to go riding in the dunes with him. He has written you an email with the details on how to get to Spinreel Park on the Oregon dunes.

Hey!

Here are the directions from Klamath Falls to Spinreel Park. First take Hwy 140 west to Medford. You might want to fill up here, gas was much cheaper in Medford than any place else on the trip. Take I-5 North for a little over 100 miles until you get to the second exit at Sutherlin. Take this exit and at the end of the off-ramp take a left (west) on Hwy 138, which ends at Elkton. Take a left here, this is Hwy 38. When you are going through Elkton stop off at the Pastry Mill. Their Cranberry, Walnut, Carmel, Orange Sticky Buns are incredible! ;-) Take Hwy 38 to Reedsport where it T-bones into Hwy 101. Take Hwy 101 until you get to the exit that announces Spinreel Park. This is about 12 miles from Reedsport.

I'm really looking forward to this weekend. It should be a blast!

Storm

3.10 Programming Exercises

1.  Write the pseudocode for asking a user to input the radius of a circle. Once you have the radius, do the necessary calculation and display the area of the circle. For the value of pi, please use 3.1416.

2.  To gain some additional experience with your particular development environment, enter in, build, debug (if necessary), and execute the following program. (Notice the use of the ‘ 'in the following code.)

images

3.  Write a C++ program to display your name and your age (hint: you will need to use cout). Make it a point to include the <iostream> header file.

3.11 Team Programming Exercise

Remember your old pen-pal friend from another country (you know, from the last chapter)? Well, now she is wondering why it is that while most of the world uses the metric system, the United States does not. While you don't necessarily want to debate the various political issues associated with this topic, you are willing to help her with the conversion of miles to kilometers problem. As you can see, the complexity of the problem is a bit more challenging than the last. She asks you to review the following pseudocode solution for outlining the steps required to convert a given distance entered by someone in kilometers to miles and help her determine if it is logically correct. Even though we just got started with pseudocode, you again agree to help her out.

In an effort to help you judge the accuracy of the algorithm below, your friend tells you the following information:

•  She prefers the metric system

•  A kilometer is 1000 meters

•  One kilometer is less than one mile

•  Kilometers per mile is approximately 1.6093 kilometers

Use the following questions to aid in your evaluation:

 1.  We know that 15 miles is approximately 24.14 kilometers. Using this information, how might you be able to actually prove that her solution is logically correct? If there is a problem, fix it!

 2.  What suggestions do you have to improve the overall readability of her pseudocode?

Problem: Write the pseudocode to ask a person to enter a distance in miles and then display the converted distance in kilometers. You will likely need to refer to some of the preceding background information.

 

images

Write your response to each of the preceding questions (1 and 2). In addition, rewrite the entire solution, addressing all of your concerns and correcting any errors. Make it a point to keep readability in mind as you rewrite your solution.

3.12 Answers to Chapter Exercises

Section 3.3

1.  Wrong slashes, change to //.

2.  For an inline comment, change to //; for a block comment, add the */ at the end of the comment. The /* */ is a matched set; you can't have one without the other.

3.  Replace the ending /* with */.

4.  You can't nest block comments. One comment must end before the next one starts.

5.  The // is for single-line comments only. To fix, either replace the // with the /* and */ combination or place the // at the beginning of each line.

Section 3.4

1.  Remember, C++ is case sensitive; therefore, the “M” in “Main” must be lowercased.

2.  No semicolons after function headers.

3.  Curly braces are used to encapsulate statements, not parentheses. The return statement should be placed between { and }.

4.  The “R” in “Return” needs to be lowercased.

5.  The braces are reversed.

Section 3.5

1.  The “I” in “Include” needs to be lowercased.

2.  Although legal with the default settings in VS, it may not work for all compilers. It is always recommended to reserve the “ ” for user-defined header files. Replace the “” with <>.

3.  Wrong symbols; replace the ( ) with < >.

4.  Remember, no semicolons after preprocessor directives.

5.  In Windows, everything is fine. In a case-sensitive operating system like UNIX, the compiler would not be able to find the header file. Therefore, it is safer to make all header files lower-case.

6.  “Using” must be all lowercase, and there must be a semicolon after the using statement.

7.  The using statement must be after the #include.

8.  There is a colon missing. The :: is required between “std” and “cout”.

9.  There needs to be a semicolon at the end of the using statement.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.76.204