1. Trang chủ
  2. » Khoa Học Tự Nhiên

C++ for business programming, 2nd ed 2006

1,6K 136 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 1.550
Dung lượng 6,87 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Most high-level languages are portable in the sense that a program written in a high-level languageshould execute, with minor modifications, on several different computer systems.. Our F

Trang 1

Pages : 848

This text provides a student-friendly, highly readable introduction

to C++ programming for beginning programming students, especially those majoring in Information Systems and Business It guides readers through complete and clear descriptions of sample programs, with a wealth of exercises included along the way to help reinforce the important points of each chapter Throughout the text, a strong emphasis is placed on business applications, rather than those in mathematics or computing.

Trang 2

Section 2.2 Solving Problems with Real Numbers 52 Section 2.3 More on Arithmetic 64 Section 2.4 Three Difficulties When Displaying Decimal Numbers with

Section 3.1 Relation Conditions 80 Section 3.2 Indefinite Iteration: The while and do Statements 83 Section 3.3 Solving a Problem with Indefinite Iteration 96

Trang 3

Section 5.1 The Function Concept 175 Section 5.2 User-Defined Functions that Return a Value 191 Section 5.3 Programs that Use Functions 203 Section 5.4 The C++ Math Library Functions 227

Chapter 9 User-Defined Data Types and Tables 363 Section 9.1 The typedef and enum Statements 364

Section 9.3 Arrays of Structures: Tables 379 Section 9.4 Structures, Functions, and Pointers 407

Trang 4

Chapter Review 424

Chapter 10 The string Class: An Introduction to Classes and Objects 426 Section 10.1 Objects, Classes, and Object-Oriented Systems 427 Section 10.2 Introduction to string Objects 430 Section 10.3 Operations on string Objects 438 Section 10.4 Making Decisions with Strings 444 Section 10.5 Functions and string Objects 446 Section 10.6 Manipulating string Objects 451 Section 10.7 Putting Strings to Work 458 Section 10.8 Arrays of Strings 470

Chapter 11 Programmer-Defined Classes and Objects 476 Section 11.1 Declaring Objects and Classes 476 Section 11.2 A More Useful Class Accessor and Mutator Methods 487 Section 11.3 Constructor Overloading and Destructors 496 Section 11.4 Default Arguments and Object Assignment 504 Section 11.5 General Function Overloading and Function Templates 511

Chapter 12 Manipulating Objects 519 Section 12.1 Using Arrays, Pointers, and Dynamic Memory Allocation 520 Section 12.2 The Copy Constructor 528 Section 12.3 Using const with Classes 540 Section 12.4 Objects, Functions and Pointers 556 Section 12.5 Dynamic Allocation of Objects 581 Section 12.6 Static Data Members and Functions 588

Trang 5

Chapter Review 727 Chapter 15 Special Topics: Friends, Operator Overloading, Macros, and

Section 15.2 Overloading Basic Arithmetic Operators 738 Section 15.3 Overloading Assignment and the this Pointer 745 Section 15.4 Overloading the Insertion and Extraction Operators 754 Section 15.5 Overloading Compound Assignment Operators 763 Section 15.6 Overloading Relational Operators 768 Section 15.7 Overloading Unary Operators 775 Section 15.8 Macros and Inline Functions 779

Section A.1 A Model Computer System 791 Section A.2 Data RepresentationCharacters 794 Section A.3 Data RepresentationIntegers 797 Section A.4 Data RepresentationReal Numbers 799

Trang 7

The author and publisher of this book have used their bestefforts in preparing this book These efforts include the

development, research, and testing of the theories and

programs to determine their effectiveness The author andpublisher make no warranty of any kind, expressed or implied,with regard to these programs or the documentation contained

in this book The author and publisher shall not be liable in any

Trang 8

event for incidental or consequential damages in connectionwith, or arising out of, the furnishing, performance, or use ofthese programs.

Trang 9

[Page xv]

Trang 10

C++ for Business Programming, Second Edition is an

introduction to C++ programming The power of C++ lies in itsobject-oriented extensions of the C language However, we

believe that for beginning students it is best to learn the basics

of programming without the extra encumbrance of having tolearn object-oriented concepts Therefore, the book is dividedinto two sections Part I, "Basic C++," covers the proceduralparts of C++ Part II, "Object-Oriented Programming," coversall the essential object-oriented ideas through inheritance andpolymorphism

Unlike most books on C++, which emphasize applications tocomputing or mathematics, this book emphasizes business

applications Therefore, the book is most appropriate for

business and information systems students The entire book can

be covered in one semester in a class of students who have agood background in programming in another language In such

a class, it is possible to quickly cover the essential programmingconstructs from Part I and then concentrate on object-orientedconcepts and programming in Part II For students who havelittle programming experience, we suggest covering Part I inone semester and Part II in a second semester The material inPart I can be supplemented as needed by material from

Appendix A, "Computers and Data," and Appendix B, "ProgramControl."

Throughout the book, we emphasize good pedagogy

Each chapter begins with a set of learning objectives

Each chapter ends with a review section that includes

important terms, a chapter summary, and review exercises

Trang 11

Important definitions, concepts, and rules are appropriatelyhighlighted in notes

Programming tips and pitfalls are noted in the margins ofthe text

One of the best ways to learn a programming language is toread programs in that language Therefore, every importantidea is illustrated in an example program and accompanyingoutput There are approximately 150 complete programs inthe text, each of which we very carefully explain

[Page xvi]

The book contains over 800 exercises of varying types andlevels of difficulty These exercises are placed at the end ofeach section rather than at the end of each chapter so

students can immediately reinforce their new knowledge.These exercises include exercises, experiments, and

programming problems

Almost every section contains exercises on the syntaxand semantics of C++ Most of these are of the paperand pencil type, although some require writing a simpleprogram

The experiments, which ask the student to investigatevarious aspects of the C++ language, are a unique

feature of the exercise sections The experiments

improve the student's understanding of the finer points

of C++ and help the student avoid common errors

made by beginning programmers

Trang 12

The programming problems, which range from 10-20-of several user-defined functions and/or classes, arefound in most sections of the book The chapter-

illustrative programs and programming problems

emphasize the business applications of C++

The book conforms to the ANSI C++ standard All

illustrative programs, however, can easily be adapted tononstandard compilers Therefore, the book can be usedwith any C++ compiler

Topics are introduced on a need-to-know basis to providemotivation for the student Therefore, the book is not

encyclopedic in its coverage of C++ In some cases, all therelevant ideas surrounding a topic are spread throughoutseveral sections or chapters

Appendix A, "Computers and Data," and Appendix B,

"Program Control," provide supplementary material forstudents who have a weak background in computing

Appendixes A and B contain exercises

Trang 13

Changes From the First Edition

The terminology and program constructs used have beenupdated to conform to current practice

Several sections have been labeled as optional to improvethe flow of the exposition and enable the reader and

instructor to concentrate on the more important concepts

In some chapters, notably Chapters 2 and 5, material hasbeen rearranged to improve readability

The book now distinguishes C-style strings from objects inthe string class

[Page xvii]

To help students transition from Part I to the object-oriented concepts in Part II, we include a transition chapter,Chapter 10, on the C++ string class Object-oriented

concepts are introduced in this chapter so that students canbegin instantiating, using, and manipulating string objects

Trang 14

without having to worry about how to define a class.

Trang 15

arithmetic Chapter 2, "Real Numbers," introduces the float and

double data types, the compound assignment, and incrementand decrement operators

statements, and the switch statement

Chapter 5 introduces the important concept of functions

Because the function is new to most students, the concept isdeveloped graduallyfirst with functions that do not return a

value, then functions having arguments, and, finally, functionsthat return a value We also include a discussion of scope andduration An entire section is devoted to discussing three

programs that use functions Special care is taken to show howthe program logic is modularized into functions The chapterends with a discussion of the C++ Math Library functions

Chapter 6, "Arrays," shows how to properly define an array andreference its elements Care is taken to show how to use a for

loop to process the elements of an array We also cover in somedetail how to sort an array using the standard bubble sort

Finally, we show how to declare and process multidimensionalarrays

Trang 16

applying them to C-style strings Illustrative programs showhow to count characters in a string, display a string in reverse,and count words in a string We also discuss arrays of stringsand arrays of pointers

Chapter 8, "Pointers, Arrays, and Functions," reinforces thestudent's knowledge of strings and pointers Call by addressusing pointers, call by reference, passing arrays as functionarguments, and functions that return pointers are discussed indetail We also cover some useful string library functions andcharacter classification and conversion functions We also

discuss the use of dynamic memory allocation using the new and

delete operators

Chapter 9, "User-Defined Data Types and Tables," discusses

typedef, enumerated types, and structures Special attention isgiven to the use of structures in defining tables A major

application involves sorting and searching a table (an array ofstructures), including both sequential and binary searches Thechapter also discusses pointers to structures and using them asfunction arguments This chapter can be omitted if time is aconsideration

using the built-in string class Sections discuss how to performoperations on string objects, how to manipulate string objectsand make decisions with string objects, and how to use string

objects with functions Upon completion of this chapter,

Trang 17

The material in Chapters 1113 is unified through the gradualdevelopment of a Savings Account class As new object-orientedprogramming (OOP) concepts are introduced, they are added tothe Savings Account class Chapter 11 introduces the reader touser-defined classes and objects We discuss how to declare aclass, instantiate objects, and code methods, constructors, anddestructors The chapter ends with a thorough discussion offunction overloading and default method arguments

Chapter 12, "Manipulating Objects," is the longest chapter inthe book Some of the topics, as outlined in the chapter

introduction, can be omitted at first reading The chapter begins

by discussing how to include array and pointer instance

variables in a class and how to use dynamic memory allocation

in a constructor and destructor Next, the chapter discusses thecopy constructor and when it is used The many ways of usingthe keyword const in C++ are then covered in detail We alsodiscuss functions that return objects as well as how to pass

objects to functions by value, pointer, and reference Several ofthe issues relating to the dynamic allocation of objects are

covered along with the uses of static class data members andmethods

Chapter 13 covers the important concept of inheritance and

related ideas We use one major example throughout most ofthe chapter to unify the material After introducing the basicterminology of inheritance and how to construct a class

hierarchy, the chapter discusses the uses of methods in such ahierarchy and the concept of polymorphism Pure virtual

methods and abstract base classes complete the chapter

Chapter 14 gives a thorough treatment of file processing in

C++ The chapter begins with a discussion of input/output (I/O)streams, the standard I/O class hierarchy, and how to processsimple text files We then show how to process a file one

character at a time Next, we discuss binary files and the

Trang 18

culminates with a random-file-access update program

Chapter 15 covers several special topics First we discuss theconcepts of friend functions and operator overloading We

emphasize the extensibility of the C++ operators by showinghow to overload the arithmetic operators, assignment, the

insertion and extraction operators, the compound assignmentoperators, the relational operators, and the unary operators Weconclude the chapter with a discussion of the use of macros andinline functions

I thank Laura Steele and Alan Apt of Prentice Hall, who madethe first edition of this book possible I also thank Kate Hargettand Mike Giacobbe for guiding me through the second edition Aspecial thanks to Dean Susan Merritt of Pace University whogave this project and me her enthusiastic support for the manyyears it took to complete Thanks also to Chin-Mei Huang forher helpful comments on an early version of the manuscript,Anna Kristoferitsch for helping to solve some of the chapter

exercises and, especially, Kenyata Millet, who spent many longhours solving the programming problems and exercises I alsothank Esther Amiri for the work she did on the exercises andprogramming problems in chapter 10 I thank Professor GeraldWohl of Pace University for having the courage to use the firstdraft of this book in his C++ courses, for catching many errorsand typos, and for providing me with many helpful commentsabout the book, and the many readers and reviewers who

provided valuable input to the second edition Finally, I thank

my familymy wife, Maria, and my sons, John and Charlesfor thehelp and love they have given me

[Page xix]

A note about the typefaces used in this book: In the program

Trang 20

[Page 1]

Trang 22

[Page 1 (continued)]

Trang 24

Why Study C++?

C++, pronounced "C plus plus," is one of the most popular

programming languages used to develop computer applications.Many corporate computing departments have adopted C++ asthe language in which to develop in-house applications Manysoftware vendors use C++ to write their application software.Why is C++ so popular and why is learning it important?

C++ is a "middle-level" language Programming languages

can be categorized as high-level or low-level Assembly

languages are low-level languages An assembly languageallows the programmer maximum control over the

computer system The programmer can directly interfacewith and control the computer's hardware and operatingsystem This control comes at a price, however Assemblylanguages are hard to learn because they are highly

symbolic and the programmer must take care of all the

details of the program Assembly-language programs arealso difficult to maintain and debug Perhaps most

important, assembly-language programs are not portable

An assembly-language program is specific to the hardwareand operating system of the computer platform on which it

is developed Thus, you cannot directly execute a PC

assembly language program on a Macintosh

[Page 2]

By contrast, high-level languages, such as COBOL, VisualBasic, and Java, are easier to learn, maintain, and debugthan assembly languages The program statements in suchlanguages use English words and familiar mathematical

Trang 25

computer system that you have in an assembly language

C++, although it is a middle-level language (and, thereforeeasier to learn and use than an assembly language),

contains many of the low-level capabilities of an assemblylanguage Thus, C++ is sometimes called a "middle-level"language It is possible through C++ to attain almost asmuch control over the computer as you can achieve with anassembly language

C++ is portable Most high-level languages are portable in

the sense that a program written in a high-level languageshould execute, with minor modifications, on several

different computer systems C++ is one of the most

portable of all the high-level languages Properly written, aC++ program can run on several computer systems with nomodifications Portability is important because it is now

common for a business to have several different types ofcomputer systems (a mainframe, minicomputers,

workstations, PCs, and Macintoshes) A properly writtenapplication in C++ should be portable to most, if not all,these systems Thus, portability eliminates the cost of

keywords (A keyword is a word that has special meaning

in the language.) C++, on the other hand, has about 60keywords Visual Basic includes extensive capabilities to

Trang 26

as simple as possible by not building things into the

defined and built-in functions and classes This gives theC++ programmer great flexibility and allows the language

language Instead, the programmer must use programmer-to be highly portable

C++ is an object-oriented extension of the C programming language Dennis Ritchie developed C at Bell Laboratories in

1972 to help write the UNIX operating system for the PDP-11 minicomputer Today many mainframes and most

minicomputers, including Reduced Instruction Set

Computing (RISC) workstations, and many Intel-based PCsand servers use the UNIX or Linux operating system Allversions of UNIX/Linux contain a version of C as their nativelanguage In other words, UNIX/Linux speaks C Why is thisimportant? Before C, a systems programmer on such a

computer system needed to use assembly language to

directly communicate with the computer Now, along withthe applications programmer, the systems programmer canuse C In the early 1980s, Bjarne Stroustrup of AT&T BellLabs developed C++, which is an object-oriented extension

of C

[Page 3]

C is an example of a procedure-oriented programming

language Thus, to develop a C program to accomplish atask, the programmer breaks down the task into a series ofsteps On the other hand, to develop an object-orientedC++ program, the programmer views the problem as a set

of interacting objects, each with its own properties and

behaviors

Trang 27

we concentrate on the non-object-oriented aspects of C++ Thiswill enable you to learn the basic constructs of C++ without theadditional burden of learning object-oriented terminology andconcepts Chapter 10, in Part II of the book, introduces you toobject-oriented ideas through the C++ built-in string class Wethen cover all the important object-oriented constructs that

make C++ one of the most powerful tools for development ofobject-oriented software

Finally, it is important for you to learn C++, even if you do notintend to become a professional programmer As a person who

is professionally involved with computers, it is important thatyou know a little of the language that many programmers

speak Not to do so would be like beginning your professionalcareer in a foreign country not knowing a word of the nativelanguage You would quickly find out that you must learn some

of the native tongue to perform efficiently on the job In a

similar way, so that you can communicate effectively with yourcolleagues, you should learn at least some of the "native

tongue" of the modern programmerC++

Trang 28

1.1 Our First C++ Program

One of the best ways to learn about the basic features of a programming language is to study a small program written in that language In this section, we discuss a simple C++ program that displays a two-line message on the computer screen Before we do

so, we discuss some general ideas about how to develop a program.

1.1.1 The Program Development Cycle

You must take several steps each time you develop a program The following six steps are typical when developing a C++ program See Figure 1.1.

Figure 1.1.

(This item is displayed on page 4 in the print version)

Step 1: Define the Problem

It is very important that you understand the problem you are trying to solve Make sure you read the problem specifications carefully Know what data is to be input into the program and what form that data should be in Also, know what processing has to

be done to that data Finally, determine what the expected output is supposed to be and what form the output must take.

Trang 29

calculator The program is to ask the user (the person running the program) to enter two numbers, then the program is to output the sum of the numbers Before you start doing anything, you have to define this problem more completely For example, should the program ask the user to enter the numbers? If so, how should the program ask? What kind of numbers are to be input? Must they be whole numbers or can they be decimal numbers? Should the numbers be input one number per line, or can they both

be input on one line? After the numbers are input and added, how should the result be displayed? Do you want the input numbers output along with the sum, or do you just want to output the sum? If you want the input numbers as well as the sum to be

output, how do you want it donein column format or on one line?

[Page 4]

As you can see, there are many questions to ask even in this simple problemand we did not ask any questions about the processing, because adding is a simple calculation Imagine how complex it would be to calculate a person's income tax!

The important point here is to ensure that you solve the correct problem Make sure that you understand exactly what you have to do before you start the next step in the development cycle If you are not sure what you need to do, ask the person who wants you to develop the program If you are writing the program for yourself, then you have

represent only the basic program control structures.

Figure 1.2.

(This item is displayed on page 5 in the print version)

Trang 30

Pseudocode avoids the syntax of a programming language and, instead, emphasizes the design of the problem solution There is no standard form of pseudocodeyou make

up your own rules The only guideline is that the meaning of the pseudocode should be clear to anyone reading it We shall include a description of the pseudocode of each program control structure that we introduce in the text We shall design most programs

in Part I of this book using pseudocode.

[Page 5]

When you design a program, it is important to check its logic before you start to write the program code itself If possible, have a friend or coworker check your program design The program designer is frequently too close to his or her design to see some errors.

Step 3: Code the Program

Note that in some cases, you do steps 3, 4, 5, and 6 (which follow) in an Integrated

Development Environment (IDE) Examples of IDEs are Visual Studio.NET and

Borland Enterprise Studio for C++ for the Windows platform, and Code Forge for the Linux environment and KDevelop for the UNIX environment All the steps are

performed selecting from pull-down menus or clicking icons All compiler error

messages are listed in a window separate from the edit window (see step 4) When you execute your program (see step 5), it executes in a separate window At no time do

Trang 31

After you complete and check the program design, code the program To code a

program means to translate the design from step 2 into a computer programming language (C++, in our case) Code the program by entering it into your IDE's text editor, or any text editor on your computer system Make sure that you save the

workstation is different from the machine language of a Macintosh, which is different from the machine language of an IBM PC, and so on Because machine language is in binary, it is difficult to write and find errors in machine language programs.

Because a computer understands only its own machine language, it cannot execute high-level or middle-level language instructions directly The computer, using a

program called a compiler, must translate middle-level and high-level language

programs into equivalent machine language programs A compiler is a specialist It translates only one high-level or middle-level language into a specific machine

language A PC-based C++ compiler translates C++ into PC machine language The compiler cannot translate a different language (such as Java) and cannot be used on a different type of computer (such as a Macintosh.)

A compiler has two main functions First it checks the source program for syntax

errors Syntax errors are errors in the grammar of the programming language If

there are any fatal syntax errors (that is, errors so severe that the compiler does not understand the statement and cannot translate the statement into machine language), the compiler will stop and notify you of the errors it found If the compiler finds no fatal errors, it translates each high-level language instruction into one or more machine language instructions This machine language version of the source program is the

It is the executable code that the computer executes.

The steps necessary for you to compile and link a program depend on the computer system and compiler on which you develop the program, and the IDE you use Some

Trang 32

IDEs simply require selecting the compile and link options from pull-down menus Some IDEs require that you create a project in which to run your program Other IDEs require executing one or two statements at command level to compile and link a program Consult your program IDE's manual or online help for instructions on the procedure you must follow.

Step 5: Execute the Program

Once you have compiled and linked the program, you are ready to execute the

program Executing the program is usually quite simple In some IDEs, all you need to

do is select the execute option from a menu or click an icon On other systems, you need to execute the program at command level Consult your program development environment user's guide for the procedure you must follow.

[Page 7]

Step 6: Test and Debug the Program

Even if a program executes, it does not mean that the program is correct Even if a program gives correct results using some data, it does not mean that the program will give correct results using another set of data Make sure that you test your program under as many conditions as possible to try to catch errors.

printed version of the program.

Errors in Step 4: If the compiler finds any fatal errors in your program, it will not

Trang 33

a list of error messages detailing the type and location of each error the compiler found Then, you must go back to step 3, correct your errors, and start the

process over Besides fatal errors, the compiler also may advise you of what it

thinks are mistakes The compiler usually calls these warnings Warnings are not

serious enough to stop the translation, but the compiler thinks you should be

made aware of them If the compiler issues warnings, the compilation will take place However, you should try to correct the source of these warnings before you execute the program unless you coded the source of the warning on purpose.

Statements that cause the compiler to issue warnings can cause some very subtle errors in program output when you execute the program In short, do not execute your program until you have removed all syntax errors.

After a successful compile, there can be an error in the linking process Usually, a linker error is caused by the inability of the linker to resolve an external

reference The most common cause of this error is the misspelling of the name of

an external program The linker cannot find the misspelled program because it does not exist Whatever the cause of the linker error, you must find and correct it.

[Page 8]

Errors in Step 5: Assuming the compilation and linking are successful, you can

execute your program Two types of errors can now occur First, the program may end during execution because it cannot execute a particular instruction This is a

run-time error When a program abnormally ends, the computer displays a

message showing the type of error that occurred You must now locate the cause

of the error (which could be in the data processed by your program, not in the program itself) and make the necessary changes Many compilers have

techniques that you can use to locate run-time errors These techniques include step-by-step tracing of program instructions and the ability to stop the program

at a predetermined place to inspect the values of variables Consult your

compiler's user's guide or on-line help for instructions on how to locate run-time errors.

Errors in Step 6: While testing your program with different sets of data, errors

can occur that are difficult to detect In fact, they could go unnoticed Although a program executes, produces output, and ends successfully, it is not necessarily correct Check your output to see if it is unreasonable or if it contains obvious

errors If so, you must find the cause of the error At this point in the program

development cycle, the error is probably a logic error The compiler checks the

program for syntax errors, but it cannot check for errors in logic Faulty program design causes most logic errors If your program contains a logic error, you must find its cause (which is sometimes very difficult), go back to step 2, redesign,

recode, reenter, recompile, relink, and retest the program (and hope that you do not introduce new errors along the way).

Occasionally, faulty coding causes logic errors Faulty coding is code that is

syntactically correct but incorrectly translates the program design into program code If your program contains faulty coding, locate and correct the faulty code, and then reenter, recompile, relink, and retest the program As we work through this book, we

Trang 34

The general rule of program development is catch errors early A mistake in step 2

might not show until step 6 If this happens, you must go back to step 2 and start the cycle again This wastes your time, computer time, and money Be cautious, and work slowly and deliberately If you are careful at the beginning of program development, your efforts will pay off in the end.

1.1.3 Displaying a Two-Line Message: dem01-1.cpp

The following is our first C++ program, dem01-1.cpp, followed by its output The program contains features of C++ that we will use throughout this book Read the program carefully After the program code, we explain each line of the program // dem01-1.cpp

Trang 35

the two characters // and continues to the end of the line The first comment gives the name of the program and the second gives the author of the program A comment is not an executable statement That is, a comment does not result in the computer taking any action Comments, which can appear anywhere in a C++ program, help to describe parts of the program and are a valuable documentation tool For example, comments might describe what a program's variables represent or the purpose of a section of the program Remember that comments are not executable statements and, therefore, the C++ compiler ignores everything from // to the end of the line.

Comment your programs to explain their code You can follow the style that we use in the programs in this book, although programmers frequently use other commenting styles Be sure to include at least the name of the program and your name as

comments in your own programs.

The first comment shows that the name of this program is dem01-1.cpp We use the convention that a C++ source-code program name should be eight or fewer characters

in length (the characters can be letters, digits, and the hyphen), followed by the cpp file-name extension This naming convention conforms to the requirements of most C++ compilers (Note: Many UNIX/Linux C++ compilers require the extension C on the name of a C++ source-code file.)

There is a blank line separating the two comment lines in dem01-1.cpp You can insert blank lines anywhere in a C++ program We shall separate the important parts of each program by one or more blank lines to enhance the readability of our program code Comments can span several lines, as shown by the following.

statement of the function main()

A function in C++ can either produce, or return, a value that can be used by the

system or it can produce no value at all The word int that precedes the word main()

Trang 36

tells the C++ compiler that main() produces an integer value In Chapter 5, we shall discuss how to write functions that do not produce a value For now, place the word int

before the word main()

The statements in main() must be enclosed in braces { } Thus the name main() is followed by a left brace {, which begins the function main() The left brace is followed by the program statements The program ends with the matching right brace } When program execution reaches this matching right brace, the program stops Code the left and right braces in main() in column one and indent the program statements two

spaces This indenting convention, which we use throughout the book, makes the program easier to read.

Each cout statement in dem01-1.cpp ends in a semicolon Semicolons are very

It is very important to keep in mind that C++ is case sensitive That is, when coding

C++ statements there is a difference between uppercase and lowercase letters Coding int Main()

is incorrect because we used an uppercase M instead of a lowercase m in the word main When a C++ program begins executing, it looks for a function named Main() , not a function named main() Later, we shall adopt conventions for naming various C++

program elements These conventions will allow the use of uppercase letters to help us

Trang 37

recognize the type of element each name represents Until then, use lowercase letters for everything except what appears inside double quotes " ", where you can use whatever combination of letters you require.

2 A function The function main() can use any function whether it is a user-defined

function (one that the programmer defines and codes) or a standard library function (a precoded function that is part of the C++ system) We shall learn

Trang 39

cout << "It works!!!" << endl;

After the string "This is our first C++ program." is sent to cout , the statement sends endl , which causes the screen cursor to move to the beginning of the next line Thus, more than one thing can be sent to cout in one statement by "cascading" the << operator When several insertion operators are used in the same cout statement, read the first one as "gets" or "is sent" and the subsequent ones as "followed by".

This is our first C++ program.

The second of the two statements in our program displays "It works!!!" and then sends

endl to cout , which causes the cursor to move to the beginning of the next line.

It works!!!

The net effect is the following output.

This is our first C++ program.

It works!!!

One cout statement can display data on several lines For example, the following cout

produces the same output as the two cout statements of dem01-1.cpp.

[Page 13]

cout << "This is our first C++ program." << endl << "It works!!!" << endl;

Trang 40

The last statement executed by main() should be the return statement As noted

previously, we declare the function main() to produce an integer value The return 0 ; statement does two things First, it ends the execution of main() Second, it sends the integer value 0 back to the operating system to indicate that the program ended

The #include directive causes the preprocessor to replace the line containing the #include

directive with the text of the named header file (so-called because it usually appears

at the beginning of the program) that appears inside the angle brackets < > Thus, the text of the named header file effectively becomes part of your program and is

Ngày đăng: 25/03/2019, 16:42

w