introduction to programming with c++ comprehensive version chapter 1

29
Pnnr 1 FUnUDAMENTAL$ : rt,. ,', i., r, .,-': , ' ,o;.i'!., r ,i t*".;riil 'rr I ' The fint part of the book is a stepping stone that will prepare you to embark on the journey of learning C++. You will begin to know C+r and will develop fundamental programming skills. SpecificallS you will learn how to write simple C++ programs with primitive data types, control statements, functions, arays, pointers, and recursion. Chapter 1 Introduction to Computers, Programs, and C++ Chapter 2 Primitive Data Types and Operations Chapter 3 Selection Statements Chapter 4 Loops Chapter 5 Functions Chapter'6 -::,i i: *;1r +: )':.'i:

Upload: nurulwahyuni

Post on 12-May-2017

231 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introduction to Programming with C++ Comprehensive Version chapter 1

Pnnr 1

FUnUDAMENTAL$

: rt,. ,', i., r, .,-': , ' ,o;.i'!., r ,i

t*".;riil 'rr I '

The fint part of the book is a stepping stone that will prepare you to embark on thejourney of learning C++. You will begin to know C+r and will develop fundamental

programming skills. SpecificallS you will learn how to write simple C++ programs withprimitive data types, control statements, functions, arays, pointers, and recursion.

Chapter 1

Introduction to Computers, Programs, and C++

Chapter 2Primitive Data Types and Operations

Chapter 3Selection Statements

Chapter 4Loops

Chapter 5Functions

Chapter'6

-::,i i:

*;1r+:

)':.'i:

Page 2: Introduction to Programming with C++ Comprehensive Version chapter 1

basic computer skills

recursion

sorting algorithms

Prerequisites for Part IThis book does not require any prior programming experience, nor any mathematics,other than elementary high school algebra and basic computer skills such as usingWindows, Internet Explorer, and Microsoft Word.

You may cover the concept and simple examples of recursive programming in$$8.1-8.3 in Chapter 8, "Recursion," after Chapter 5, "Functions."

You may cover Chapter 18, 'Algorithm Effrciency and Sorting," after Chapter 6,"Arrays." Tlvo simple sorting algorithms are introduced in Chapter 6. Chapter l8introduces several advanced sorting algorithms.

Basic computer skills such as using Windows,Internet Explorer, and Microsoft Word

Introduction to Computers, Programs.and C++

Chapter 2 Primitive Du,u 19: und Op"r1gl

Chapter 3 Selection Statements

Chapter 5 Functions

Chapter 7 Pointers and C-Strings

Page 3: Introduction to Programming with C++ Comprehensive Version chapter 1

-1

CTnPTER I

. :'.,:. .,,' .: , itt:ir jl;t::li:.lxt,:, :,,

Objectivesr To review computer basics, programs, and operating systems ($$1.2-1.4).

I (Optional) To reprcsent numbers in binary- decimal, and hexadecimal ($1.5).

r To know the history of C+r ($1.6).

r To write a simple C++ program ($1.7).

I To understand the C+r program development cycle ($ 1.8).

(Optional) To develop C+r using Visual C++ ($1.9).

(Optional) To develop C+r using Dev-C+r ($1.10).

(Optional) To develop C+r using command line toolson Windows ($l.ll).

(Optional) To develop C+r using command line toolson Unix ($1.12).

I

I

I g"

Page 4: Introduction to Programming with C++ Comprehensive Version chapter 1

22 Chapter I Introduction to Computers, Programs, and C++

l. I lntroductionYou use word processors to write documents, Web browsers to explore the Internet, and emailprograms to send email over the Internet. Word processors, browsers, and email programs areall examples of software that runs on computers. Software is developed using programmingIanguages. C+r is a popular and powerful programming language. Most application softwaresuch as word processors, browsers, and email progams are developed using C+r. This bookwill introduce you to developing programs using C+r.

You are about to begin an exciting journey, learning a powerful programming language.Before the journey, it is helpful to review computer basics, progr:rms, and operating systems,and to become familiar with number systems. You may skip the review in $$1.2-1.4 if you arefamiliar with such terms as CPU, memory disks, operating systems, and programming lan-guages. You may also skip $1.5 and use it as reference when you have questions regardingbinary and hexadecimal numbers.

1.2 What ls a Computer?A computer is an electronic device that stores and processes data. A computer includes bothhardware and software. In general, hardware is the physical aspect of the computer that canbe seen, and software is the invisible instructions that control the hardware and make it per-form specific tasks. Computef programming consists of writing instructions for computersto perform. You can learn a programming language without knowing computer hardware,but you will be better able to understand the effect of the instructions in the program if youdo. This section gives a brief introduction to computer hardware components and theirfunctionality.

A computer consists of the following major hardware components, as shown in Figure l. L

r Central Processing Unit (CPU)

I Memory (main memory)

I Storage Devices (disks, CDs, tapes)

I Input and Output Devices (monitors, keyboards, mice, printers)

I Communication Devices (modems and network interface cards (NICs))

hardware

software

Ftcunt l.l A computer consists of CPU, memory hard disk, floppy disk, monitor, printer,and communication devices.

The components are connected through a subsystem called a Dns that transfers data betweenthe components.

1.2.1 Central Processing UnitThe central processing unit (CPA is the brain of a computer. It retrieves instructions frommemory and executes them. The CPU usually has two components: a control unit and an

arithmetic/logic unit. The control unit controls and coordinates the actions of the other

nput IDevices I

., KeyboardMouse

output IDevices

I.g., Monitor

Printere.g., Disk, CD,

and Tapee.g., Modem, e.g

and NIC

CPU

Page 5: Introduction to Programming with C++ Comprehensive Version chapter 1

components. The arithmetic and logic unit performs numeric operations (addition, subtrac-

tion, multiplication, division) and logical operations (comparisons).

Today's CPU is built on a small silicon semiconductor chip with millions of transistors.

Ttre speed of the CPU is mainly determined by clock speed. Every computer has an internal

clock. The faster the clock speed, the more instructions are executed in a given period of time.

The clock emits electronic pulses at a constant rate, and these are used to control and syn-chronize the pace of operations. The unit of measurement is called a hertz (Hz), with I hertz

equaling I pulse per second. The clock speed of computen is usually measured in megahertz(MHz) (l MHz is I million Hz). The speed of the CPU has been improved continuously. Ifyou buy a PC now, you can get an Intel Pentium 4 Processor at3 gigahenz (GHz) (l GHz is

1000 MHz).

1.2 What ls a Computer? 23

speed

hertz

megahertz

gigahertz

1.2.2 MemoryComputers use zeros and ones because digital devices have two stable states, referred to as

zero and one by convention. Data of various kinds, such as numbers, characters, and strings,

are encoded as a series of Dits (binary diglls: zeros and ones). Memory stores data and pro- bit

gram instructions for the CPU to execute. A memory unit is an ordered sequence of bytes, byte

each holding eight bits, as shown in Figure 1.2.

Memory address Memory contenttlYY

01001010

01100001

01110110

01100001

00000011

2000

zmL2ffi22003

2W

Encoding for character'J'

Encoding for character 'a'

Encoding for character'v'Encoding for character 'a'

Encoding for number 3

Ftcunr 1.2 Memory stores data and program instructions.

The programmer needs not to be concerned about the encoding and decoding of data,

which is performed automatically by the system based on the encoding scheme. The encoding

scheme varies. For example, character 'J' is represented by 01001010 in one byte in the pop-

ular ASCII encoding. A small number such as 3 can be stored in a single byte. If a computer

needs to store a large number that cannot fit into a single byte, it uses several adjacent bytes.

No two data items can share or split the same byte. A byte is the minimum storage unit.

A program and its data must be brought to memory before they can be executed. A mem-

ory byte is never empty, but its initial content may be meaningless to your Program. The cur-

rent content of a memory byte is lost whenever new information is placed in it.Every byte has a unique address. The address is used to locate the byte for storing and

retrieving data. Since the bytes can be accessed in any order, the memory is also referred toas MM (random-access memory). Today's personal computers usually have at least 128 RAM

megabytes of RAM. A megabyte (abbreviated MB) is about 1 million bytes. For a precise megabyte

definition of megabyte, please see http://en.wikipedia.org/wikifvlegabyte. Like the CPU, memory megabyte URL

is built on silicon semiconductor chips containing thousands of transistors embedded on theirsurface. Compared to the CPU chips, memory chips are less complicated, slower, and less

expensive.

Page 6: Introduction to Programming with C++ Comprehensive Version chapter 1

1.3 Programs 25

The numeric keypad, located on the right-hand corner of the keyboard, is a separate set of numeric keypadnumber keys for quick input of numbers.

Arrow &eys, located between the main keypad and the numeric keypad, are used to move anow keythe cursor up, down, left, and right.

The Insert, delete, page up, and, page down keys, located above the arrow keys, are used inword processing for performing insert, delete, page up, and page down.

The Mouse

A mouse is a pointing device. It is used to move an electronic pointer called a cursor aroundthe screen or to click on an object on the screen to trigger it to respond.

The MonitorThe monitor displays information (text and graphics). The resolution and dot pitch determinethe quality of the display.

The resolution specifies the number of pixels per squiue inch. Pixels (short for "picture scrcen resolurionelements") are tiny dots that form an image on the screen. A common resolution for a l7-inchscreen, for example, is 1024 pixels wide and 768 pixels high. The resolution can be set man-ually. The higher the resolution, the sharper and clearer the image is.

The dot pitch is the amount of space between pixels. Typically, it has a range from 0.21 to dot pitch0.81 millimeters. The smaller the dor pitch, the better the display.

1.2.5 Communication DevicesComputers can be networked through communication devices. The commonly used commu-nication devices are the dialup modem, DSL, cable modem, and network interface card. Adialup modem uses a phone line and can transfer data at a speed up to 56,000 bps (bits per modemsecond). A DSL (digital subscriber line) also uses a phone line and can transfer data at a speed DsLtwenty times faster than a dialup modem. A cable modem uses the TV cable line maintainedby the cable company. A cable modem is as fast as DSL. A network interface card (NIA is a NICdevice that connects a computer to a local area network (I-41,t). The LAN commonly is used LANin business, universities, and govemment organizations. A typical NIC called I1BaseT cantransfer data at l0 mbps (million bits per second). mbps

1.3 ProgramsComputerprogrcns, known as software, are instructions to the computer. You tell a computer sofrwarewhat to do through programs. without programs, a computer is an empty machine. comput-ers do not understand human languages, so you need to use computer languages to communi-cate with them.

The language a computer speaks is the computer's native language or machine language.The machine language is a set of primitive instructions built into every computer. Machine machine languagelanguages are different for different types of computers. The instructions are in the form ofbinary code, so you have to enter binary codes for various instructions. Programming using anative machine language is a tedious process. Moreover, the programs are highly difficult toread and modify. For example, to add two numbers, you might have to write an instruction inbinary like this:

1101101010011010

Assembly language is a low-level programming language in which a mnemonic is used to rep- assembly languageresent each of the machine language instructions. For example, to add two numbers, youmight write an instruction in assembly code like this:

ADDF3 R1-, R2, R3

Page 7: Introduction to Programming with C++ Comprehensive Version chapter 1

26 Chapter I

assembler

lntroduction to Computers, Programs, and C++

Assembly languages were developed to make programming easy. Since the computer cannotundentand assembly language, however, a program called assembler is used to convert assem-

bly language programs into machine code, as shown in Figure 1.3.

high-level language

source program

compiler

Frcuna 1.3 Assembler translates assembly language instructions to machine code.

Since assembly language is machine-dependent, an assembly program can only be exe-

cuted on a particular machine. Assembly programs are written in terms of machine instruc-tions with easy-to-remember mnemonic names. The high-level languages were developed inorder to overcome the platform-specific problem and make programming easier.

The high-level languages are English-like and easy to learn and program. Here, for exam-ple, is a high-level language statement that computes the area of a circle with radius 5:

sfed=5*5*3.1415;

There are over one hundred high-level languages. The popular languages are:

r COBOL (COmmon Business Oriented Language)

r FORTRAN (FORmula TRANslation)

r BASIC (Beginner All-purpose Symbolic Instructional Code)

I Pascal (named for Blaise Pascal)

r Ada (named for Ada Lovelace)

I Visual Basic (Basic-like visual language developed by Microsoft)

r Delphi (Pascal-like visual language developed by Borland)

r C (whose developerdesigned B first)

r C+f (an object-oriented language, based on C)

t Java

r C# (a Javalike language developed by Microsoft)

Each of these languages was designed for a specific purpose. COBOL was designed for business

applications and is used primarily for business data processing. FORTRAN was designed formathematical computations and is used mainly for numeric computations. BASIC, as its name

suggests, was designed to be learned and used easily. Ada was developed for the Department

of Defense and is mainly used in defense projects. Visual Basic and Delphi are used in develop-

ing graphical user intertaces and in rapid application development. C combines the power ofan assembly language with the ease of use and portability of a high-level language. C+r is pop-ular for system software projects like writing compilers and operating systems. The MicrosoftWindows operating system was coded using C+r. Java, developed by Sun Microsystems, iswidely used for developing Internet applications. C# (pronounced C sharp) is a new languagedeveloped by Microsoft for developing applications based on Microsoft .NET platform.

A program written in a high-level language is called a source prograrn. Since a computercannot understand a source program, a program called a compiler is used to translate the

Page 8: Introduction to Programming with C++ Comprehensive Version chapter 1

1.4 Operating Systems 27

source program into a machine-language program. The machine-language program is oftenthen linked with other supporting library code to form an executable frle. The executable filecan be executed on the machine, as shown in Figure 1.4. On Windows, executable files haveextension.exe.

G @ f:-..---lI sour"" Fite

,, H Compiler F.l uacline-tanguagoH U"k;;}+ | ..Executabt Et--_--jl lq___qg,_:-S Lnlg-l

Frcunt 1.4 A source program is compiled into a machine-language file, which is thenlinked with the system library to form an executable file.

1.4 Operating SystemsThe operating system (OS) is the most important program that runs on a computer to manage andcontrol its activities. You are probably using Windows (98, NT, 2000, XP, or ME), Mac OS, orLinux. Wndows is currently the most popular PC operating system. Application programs, suchas a Web browser or a word processol cannot run without an operating system. The interrela-tionship of hardware, operating system, application software, and the user is shown in Figure 1.5.

Flcuu 1.5 The operating system is the software that controls and manages the system.

The major tasks of the operating systems are:

r Controlling and monitoring system activities

r Allocating and assigning system resources

r Scheduling operations

1.4.1 Controlling and Monitoring System ActivitiesOperating systems are responsible for security, ensuring that unauthorized users do notaccess the system. Operating systems perform basic tasks, such as recognizing input fromthe keyboard, sending output to the monitor, keeping track of files and directories on thedisk, and controlling peripheral devices, such as disk drives and printers. Operating systemsalso make sure that different programs and users running at the same time do not interferewith each other.

1.4.2 Allocating and Assigning System ResourcesThe oS is responsible for determining what computer resources (cPU, memory disks,input and output devices) a program needs and for allocating and assigning them to run theprogram.

Page 9: Introduction to Programming with C++ Comprehensive Version chapter 1

1.5.1 Conversions between Binary Numbersand Decimal Numbers

Given a binary number b,,bn-1bn-2. . . b2bftg, the equivalent decimal value is

bnx2n * bn- rxzn-t * bn-2x2n-2 + ... + b2x22 + btxzt + boxzoThe following are examples of converting binary numbers to decimals:

Binary Conversion Formula Decimal

1.5 (Optional) Number Systems 29

binary to decimal

2

8

l01000

1010101I

tx2t+0x20tx2t+0x22+lxzT+0x26+lx2t +0x22 +

0x2r+0x20lx2s +0x24 +lx21+lxzo t7l

Toconvertadecimalnumberdtoabinarynumberistofindthebits bn,bn-1,bn-2,...,b2, decimal tobinaryby and bs such that

d: bnx2n + bn-t\2n-t + bn-zx2n-2 + ... r bzx22 + b1x2r + blx20These bits can be found by successively dividing d by 2 until the quotient is 0. The remaindersare b6, by b2,..., bn-2, bn-t, and bn.

For example, the decimal number 123 is 111l0l I in binary. The conversion is done as follows:

0 /. 1 --3 -/ 7 -.'i5 --30 --61

-

Quotientl- -.- l-- -.- a- --- l- ,.- l-2l t/zl t/rl t/ tl 1s-" tl ,o/ rl 6(" zl w7 7' 1 1 rJ 1 -) )026143060122

b3

Remainder

tbo

TipThe Windows Calculator, as shown in Figure 1.6, is a useful tool for performing number conver-sions. To run it, choose Program' Accessories, and calculator from the start button.

Decimal Binary

1

+b6

I

Y

b5

1

Y

b4

0Ii

b2

I

++

b1

g

Frcun: 1.5 You can perform number conversions using the windows calculator.

Page 10: Introduction to Programming with C++ Comprehensive Version chapter 1

30 Chapter I Introduction to Computers, Programs, and C+r

1.5.2 Conversions between Hexadecimal Numbersand Decimal Numbers

hex to decimal Given a hexadecimal number hnhr-1hn-2. . . h2h1hg, the equivalent decimal value is

hnx l6n r hn_tx l6n-l * hr_zx 16"-2 + ... + h2x 162 + hx16l + ft6 x 160

The following are examples of converting hexadecimal numbers to decimals:

Hexadecimal Conversion Formula Decimal

7F 7xl6r+15x160 t27

FFFF 15x163+15x162+15xl6t+15x160 65535

431 4x162+3x16l+lx160 lo73

decinul to hex To convert a decimal number d to a hexadecimal number is to find the hexadecimal disitshn, hr-1, hn-y,. . . , hZ, ht, and ig such that

d : h,x 16' + hn-rX 16'-l + hn-zx l6n-2 + ...+ hzx 162 + ht x 16r+ fto x 160

These numbers can be found by successively dividing d by 16 until the quotient is 0. Theremainders are hg, hv hz,. .., hn-2, hn-y and hn.

For example, the decimal number 123 is 7B in hexadecimal. The conversion is done as

follows:

0 ,/ Quotient

l-- -'' l-r9 7- 19 r23

0 tt2

hex to binary

7 1,1 RemainderttVYht ho

1.5.3 Conversions between Binary Numbersand Hexadecimal Numbers

To convert a hexadecimal number to a binary number, simply convert each digit in the hexa-decimal number into a four-digit binary number using Table 1.1.

Forexample,thehexadecimalnumberTBisllll0ll,whereTislllinbinary,andBisl0l I in binary.

To convert a binary number to a hexadecimal, convert every four binary digits from right toleft in the binary number into a hexadecimal number.

For example, the binary number 1l 10001l0l is 38D, since I l0l is D, 1000 is 8, and I I is3, as shown below

1r1000

38

NoteOctal numbers are also useful. The octal number system has eight digits, 0 to 7. A decimal num-ber 8 is represented as l0 in the octal system.

binary to hex

1101tl

I

D

&

Page 11: Introduction to Programming with C++ Comprehensive Version chapter 1

Taau l.l Converting Hexadecimal to Binary

Hexadecimal Binary Decimal

0

tI

2

3

4

5

6

7

8

9

A

B

cD

E

F

1.6 History of C++ 3 |

cC++

0

I

t0

ll100

l0l110

lll1000

1001

1010

l0l lI 100

I t0l

1ilO

llll

0

2

J

A

5

6

7

8

9

l0

llt2

l3

t4

l5

1.6 History of C++C, C++, Java, and C# are very similar and related. C++ evolved from C. Java was modeledafter C++. C# is a subset of C++ with some features similar to Java. If you know one of theselanguages, it is easy to learn the others.

C evolved from the B language and the B language evolved from the BCPL language. BCPLwas developed by Martin Richards in the mid-1960s for writing operating systems and compilers.Ken Thompson incorporated many features from BCPL in his B langwge and used it to createearly versions of the UNX operating system at Bell l,aboratories in 1970 on a DEC PDp-7computer. Both BCPL and B were typeless, i.e., every data item occupies a fixedJength "word"or'tell" in memory. How a data item is reated, for example, as a number or a string, is theresponsibility of the programmer. Dennis Ritchie extended the B language by adding types andother features in 197 I to develop the UNIX operating system on a DEC PDP- I I compurer. Ti:day,C is portable and hardware independent. C is widely used for developing operating systems.

C++ is an extension of C, developed by Bjarne Stroustrup at Bell labs during 1983-1985.C+r added a number of features that improved the C language. Most importantly, it added thesupport of using classes for object-oriented programming. Object-oriented programming canmake programs easy to develop and easy to maintain. C++ could be considered a superset ofC. The features of C are supported by C++. C programs can be compiled using C++ compil-ers. After learning c++, you will be able to read and understand C programs as well.

An intemational standard for C++ was created by the American National Standards tnsti-tute (ANSI) in 1998. The AN,S/ sta ndard is an attempt to ensure that C++ is portable, i.e., yourprograms compiled using one vendor's compiler can be compiled without errors from anyother vendors on any platform. Since the standard has been around for a while, all the majorvendors now support the ANSI standard. Nevertheless, the C++ compiler vendors may addproprietary features into the compiler. So, it is possible that your program may compile fineby one compiler, but have to modify the code in order to be compiled by a different compiler.

ANSI standard

Page 12: Introduction to Programming with C++ Comprehensive Version chapter 1

32 Chapter I Introduction to Computers, Programs, and C+r

1.7 A Simple C++ ProgramLet us begin with a simple C+r program that displays the message "Welcome to C+r!" on theconsole. The program is shown in Listing 1.1.

Lrsrr.rc l. I Wel come. cppinclude library

main function

commentoutput

successful return

line number

directive

header file

main function

console output

stream insertion operator

std

successful exit

comment

line comment

paragraph r'onrment

l_

2

3

45

61

89

finclude <iostream>

int maino{

// Display Welcome to C++ to the consolestd::cout << "Welcome to C++!" << std::end1;

return 0;]

Welcome to C++!

The line numbers are not part of the program, but are displayed for reference purposes. So,don't type line numbers in your program.

Line I is a compiler di rective that tells the compiler to include the i os t ream library in thisprogram, which is needed to support console input and output. The library like iostream iscalled a header file in C++, because it is usually included at the header of a program.

Every C+r program is executed from a main function. A function is a construct that containsstatements. The mainfunction defrned in lines 3-9 contains two statements. The statem€nts areenclosed in a block that starts with a left brace, {, (line 4) and ends with a right brace, } (line 9).Every statement in the block must end with a semicolon (; ) known as the statement terminator.

The statement in line 6 displays a message to the console. std: : cout stands for console out-put. The << op€rator, referred to as the stream insertion operator, sends a string to the console. Astring must be enclosed in quotation marks. The statement in line 6 first outputs the string "wel-come to C+r!" to the console, and then outputs std: : endl . Note that endl stands for end line.Sending std: : endl to the console outputs a new line and flushes the output buffer to ensure thatthe output is displayed immediately.

What is std? std stands for standard name space. std: : is placed in front of cout and endlto denote that cout and endl are in the standard name space.

The statement in line 8

return 0;

is placed at the end of every main function to exit the program. The value 0 indicates that theprogram has terminated successfully.

Line 5 is a comment that documents what the program is and how the program is con-structed. Comments help programmers to communicate and understand the program. Com-ments are not programming statements and thus are ignored by the compiler. In C++.comments are preceded by two slashes (/ /) on a line, called a line comment, or enclosedbetween /'r and'1'/ on one or several lines, called a paragraph co,rtment. When the compilersees / / , it ignores all text after / / on the same line. When it sees /':', it scans for the next '',1and ignores any text between /r, and" /.

Here are examples of the two types of comments:

// This application program prints Welcome to C++l/* This applicat'ion program prints lrlelcome to C++l *//* This appljcation program

prints Welcome to C++! *,/

Page 13: Introduction to Programming with C++ Comprehensive Version chapter 1

1.8 C++ Program Development Cycle 33

Keywords, or resem'ed words, are words that have a specifrc meaning to the compiler and keyword

cannot be used for other purposes in the program. There are two keywords: int and returnin this program.

NoteYou are probably wondering about such points as why the main function is declared this way

and why std: :cout << "We1come to C++!" << std: :end'l is used to display a

message to the console. Your questions cannot be fully answered yet. For the time being, you

will just have to accept that this is how things are cione. You will find the answers in the com-

ing chapters.

NoteLike any other programming language, C+r has its own syntax. and you need to write code that

obeys the synlax rules. The C++ compiler will report syntax errors if your prognm violates the syntax rules

syntax rules. Pay close attention to the punctuation. The redirection symbol << is two succesive

<'s. There are two consecutive colons (: ) between std and cout. [very statement in the func-

tion ends with a semicolon (; ).

CautionC++ source programs are cose-sensiliue. lt would be wrong, for example, to replace main in the case-sensitive

program with Mai n.

The program in Listing l. I displays one message. Once you understand the program, it iseasy to extend it to display more messages. For example, you can rewrite the program to dis-play three messages, as shown in Listing 1.2.

Ltsrrruc 1.2 Wel come1. cpp1 #include <iostream>2 int maino3{4 std::cout << "Welcome to C++!" << std::end1;5 std::cout << "Welcome to C++.NET!" << std::endl:6 std::cout << "Welcome to C++ Compiler!" << std::endl;7

8 return 0;e]

Welcome to C++!Welcome to C++.NET!Welcome to C++ Conpiler!

1.8 C++ Program Development CycleYou have to create your program and compile it before it can be executed. This process is

repetitive, as shown in Figure 1.7. If your program has compilation errors, you have to ltxthem by modifying the program, and then recompile it. If your pro$am has runtime errors ordoes not produce the correct result, you have to modify the program, recompile it, and executeit again.

NoteA C++ source file Wpically ends with the extension .cpp. Some compilers may accept other file .cpp source filename extensions (e.g., .c, .cp, or .c). but you should stick with the .cpp ecension to be compli-

ant with all ANSI C+r compilers.

include librarymain function

output

successful return

Page 14: Introduction to Programming with C++ Comprehensive Version chapter 1

34 Chapter I lntroduction to Computers, programs, and C++

Source code (developed by the

Saved on the disk

Stored on the diskIf compilation errors

An object file (e.g., Welcome.obj) is created.

Stored on the disk

An executable file (e.g., Welcome.exe) is created.

flcunr l'7 The C++ programming-development process consists of creating/modifying source code, compiling,linking, and executing programs.

compiler commandNoteThe c+r compiler command performs three tasks in sequence: preprocessing. compiling. andlinking. The compiler first processes the directives. The directives start with the t sign. Forexample' the inc'lude statement in line I of Listing Ll is a directive to tell the compiler toinclude a library. The compiler then translates the source code into a machine code file calledobject file, and finally. it links the object file with supporting library files to form an executablefile' On Windows, the object file is stored on disk with an .obj extension and the executablefiles are stored with an .exe extension. on uNlX, the object file has an . o extension and theexecutable files do not have file extensions.

You can develop a C++ program from a command line or from an IDE. An IDE is a soft-ware that provides an integrated development environment (lDE) for rapidly developing C++programs. Editing, compiling, building, debugging, and online help are integrated in on"graphical user interface' Just enter source code in one window or of.n an existing file in awindow, then click a button, menu item, or function key to compil,e and run the program.Examples of popular IDEs are Microsoft Visual C++, Borland C++Builde., and Dev--C++.

The following sections introduce how to develop a C++ program from Visual C++ and Dev-C+r. The use of C++Builder is provided in the supplements on the Companion Website.

IDE

If runtime errors or incorrect result

#include <iostream>int maino{' // Display Welcome to C++ to the console

std::cout << "We'lcome to C++!" << std::endl;, return 0;

Run Executable Codee.g., Welcome

Page 15: Introduction to Programming with C++ Comprehensive Version chapter 1

1.9 Developing C+r Programs Using Visual C+r 35

1.9 Developing C++ Programs Using Visual C++Vsual C++ is a component of Microsoft Visual Studio .NET for developing C++ programs. Afree version named Vsual C++ 2005 Express Edition is included in the book's CompanionCD-ROM. This section introduces how to create a project, create a program, compile, and run

the program.

1.9.t Getting Started with Visual C++Visual C++ is easy to install. If you need help on installation, please refer to Visual C++Tutorial in the supplements.

Suppose you have installed Visual C++ 2005 Express Edition. You can launch VC++ fromthe Windows Start button by choosing All Programs, Vsual C++ 2005 Express Edition,Microsoft Vsual C++ 2005 Express Edition. The Visual C++ 2005 Express Edition user

interface appears, as shown in Figure 1.8.

Ftcunt 1.8 The VC++ user interface is a single window that performs editing, compiling,debugging, and running programs.

1.9.2 Creating a ProjectTo create C++ programs in Visual C+r, you have to frrst create a project. A project is like a

holder that ties all the files together. Here are the steps to create a project:

1. Choose File, New, Project to display the New Project window, as shown in Figure 1.9.

2. Choose Win32 in the project types column and Win32 Console Application in theTemplates column. Type bookexampl e in the Name field and c : \smi th in the Loca-tion freld. Click OK to display the Win32 Application Wizard window, as shown inFigure 1.10.

3. Click Ne# to display the application settings window, as shown in Figure 1.11.

Anmfifug the Upgrade Ysr Gam Ar@de r,lxh'nre sw-f!Tue, 16 Hay 2006 15:43:21 Gt{T - Ch€ck c|n tte fre gm Iddev€b9s hil$g resdirce that tedr !dr, stePby-step, hx Sto develop )air own r6d€ gEfrEs oo SE Pc' and ents to wh a HrbfErsvG*gar@demadtEl Hl,ledbsh.e Hssgls St rts xA Sl,lon, 0l r|ay 2006 2r:35:05 GllT - The tlefi sttm il*ngs HStdter xr b a ftty functhfrg orstom ctEt cbt tEt enabts Slou to serd trstaf,t mess96 b !€ur trtTds ild fls *w E)our trxr$c cobdim rdr ttm ffiabdde rEhffik (lx{).

:

Introdu(trm to frrogm*lg LEGo HIXNToR,IS ,

ilon, Ol l'ldy 2006 2f 30:56 GltlT - Evs rsd to bud )orrorn robof? tthg t€ I.EGO tND{DSfOR},ts kt, md fE lbosoft.NgMerfacg !,ar ar stdrt expernorlr{ r*'r roboti]s ard :aontsdlo{tr rcbd frun tour Fq artmatity r$mv6 :

around ob6tades, and pby mi*. gDffifoadttE PSD(lilh.ts t{s n \/lsud C++Geafq drd l.|anaoirg \b.d...

Page 16: Introduction to Programming with C++ Comprehensive Version chapter 1

36 Chapter I Introduction to Computers, Programs, and C+r

Frcuns 1.9 You need to create a project before creating programs.

Welcomc to thc Win32 Application Wizard

Apgli€ation Setungs

a{:t'ri4Y ' :

'T#' ;

r-.:':"i." .5.: i.

;,lX$'

:F,"1..., ,," *",- .The{ lrr lho orrant For€€t sst

. .'.1 , . e '. Console applicitton '-.:1. ": .

:

Cld fr|iih from .'ry s,fidw !o acce$ th. a,rr8nt setff€e

Frcunt l.lO Win32 Application Wizard creates a project for Win32 applications.

4. Select Console application in the Application type section and check Empry project inthe Additional options section. Click Finish to create a project. You will see the projectnamed bookexampl e in the solution explorer, as shown in Figure 1.12.

Page 17: Introduction to Programming with C++ Comprehensive Version chapter 1

1.9 Developing C+r Programs Using Visual C+r 37

Important check it

Frcune l.l I Win32 Application Settings window lets you set the application type.

Solutionexplorer showsthe files in theproject

Frcuns l.t2 A project is created for C++ console applications.

1.9.3 Creating a C++ ProgramAfter you created a project, you can create programs in the project. Here are the steps to cre-ate a C++ program for L,isting l. I :

#e@tri- E lteaOer nesr Gl Rescurce Fles1- E SJrce Ees

Opetr: ttoJed...O€ate ProFct...

Announcirq tlrc Upgrade Your caole Arcade Machirre Sw.,.]lTue, 16 May 2006 16:43:21 GMT - Ch€ck out these free garne rt ldevdoper harrmg resourG that t€dr )/ou, stepby-step, tr*r U'lto devdop your own arcade games on ttre rc, and mter to win a fiilHs PenaryGabga arcade rnad|]|e!

F"ltledasharc Messer€er Starter Kit hlllon, ol May 2006 2r :36;05 Girr - Th€ trtedia share l.lesserger ffisarter lG b a fuly furEtixirg orstom chat €t that enables bl).ar to send irslant messages to )roer frtsnds and even share Hyour must colectbn lridr tlsn over a bcd area network (tAN). '

'.htrodudion to prograrnmilg LEGO lllt{DsTORllS l.l.llo{t 0l t{ay 2006 21:30:56 Gl'fT - Ever vianted to buH your ,"r,om robot? tliE the LEGo l'{lNDSroR}6 kt, and the Mitosoft .i..NET Interfdce, )lou crn start o(p€rinentiE wilh robotics ardcoertsd yorir robot fron your rc, aJtofiEtialy rEneuver ':..arilnd obctades, and pbry mr*. M

Dortr{oad th€ PSDI(

Whds l{erY h \lHrd C++cr€afixg and llan4,hg vlgrd ...

Page 18: Introduction to Programming with C++ Comprehensive Version chapter 1

38 Chapter I Introduction to Computers. Programs. and C++

l. Choose Add, Add New ltem from the context menu of the bookexample project (see

Figure 1.13) to display the Add New Item window, as shown in Figure 1.14.

Frcum l.l3 You can open the Add New Item window from the project's context menu.

g Viglal C++

iUliftr: - Data

- PropertFh€ets

:-F-t 5'_-11 );octrg t \rfirl2 :iQr-*o-;i5l,:El-.Ef.El-,f,

Antilndrg ttP Upgt-.dc Yu Gan{ Ar:dt Hrfti* S.- $TE, f 6 iby 2m6 16:43:21 GilT - Chtrt ot tlE h€ gEnr ljl(b.dop6 bilrhg rerc6 tlit teadr l/or, stepby{ep, lw SJb d€vebg 161tr oern rcadc ailn6 on UE rc, md ffts to m a $-liGhorvc&98d6(,€rEdnd I.lt'tnfRshile }ksrrgtr stdtd Kt { |Hon,-Or tEy 2006 2r:36:05 C'HT - Thc llQdb StUe r.rcerae $ |Tl-t n b a n-ry turctirrE crEto.n ciat tu that mbts ElIe! send irstanl rt$g€s b )€ur ffi ild wen stBre fn-- |ru*ohcurfihdmw€rabcdnean€tnort(ux} l*l

|tutim to rroga-r*a lrs) xtu)sroRxs fil- ' Dl l.{ry 2005 2l:30:56 C,l'lT - €v6 w{€d to h.# }d, Hpbot? ts'g Op LEGO lolD5'ro$4s kr. ild dp l,bm{t g|Fftrfe, )€rJ cn ffi uperrmBE v,ldt roboG Jrd El

-!| your robot trm 'rdr rc. rnondtaly manowa arcrdfl

oHaes,ild pbynircf*t lh€ Aprl20fi, DitrlX SOX

ifon, Ol l{av 2006 2r:35:43 GHT - ltis S0( tldnt€s tfr. toobne€ded to buld ottng-edge, m€d*rEh, rt€ractvc a9d6ttIi(;erti.rg ttnrtrd witlt \/Ardl Cr. I rpra$ fdibnTE, 07 l'lar 2006 01 :28:17 C+tf - Dsff t s C++ txF63 Edtittaturer, provir6 a Oiit€d lil ild a Hqr-dd sE r :J

6L|U

R€bid

Chrl

Project OIy

Ar$omA.|6 R.*3-.

Tod ard ord€r...

Ratere'Ecs-

Add vJeb Re{trffi^.

Set6 st3tlrp Proj€ct

Debrg t

,Pa----*_Y9f""L "Prop6tis

FtcuRr l.l4 You can specify the file type, name, and location to create a file.

Page 19: Introduction to Programming with C++ Comprehensive Version chapter 1

1.9 Developing C++ Programs Using Visual C++

2. Choose Code in the Categories column and C++ File (.cpp) in the Templates column.Enter Uelcome in the Name held and c:\smith\bookexamp'le\bookexample inthe l,ocation freld. Click A dd to create the file, as shown in Figure I . 15.

Ftcunr l. I 5 Welcome.cpp is created in the project.

3. Enter the code for Welcome.cpp exactly fiom Listing 1.1, as shown in Figure 1.16.

FtcuRE l.l6 The source code for Welcome.cpp is entered.

1.9.4 Compiling a C++ ProgramAfter you created a program, you can compile it. You may compile it by choosing Build,Compile, or press Ctrl+F7, or choose Compile in the context menu for Welcome.cpp, as

shown in Figure 1.17.

39

Sofrtix|'bookexample' (t projeC)e- GP boo&€radrple

:- AneaOernesr' f nesoureFesE- E SourceFs

- €w*nr.cpp

linclude <iostrean>

lint arainoIr| // oisptay flelcone to c.|+ to the

I std::cout << 'l{elccEle to c++!i <<

I returtr 0;

L' 6eTt ?rlocfrr.ill $IU0l I

, * lsEremrilros$Ast *

[tffit

Page 20: Introduction to Programming with C++ Comprehensive Version chapter 1

40 Chapter I Introduction to Computers, Programs, and C++

Frcunr l.l7 Choose the Compile command to compile the prograrn.

1.9.5 Running a C++ ProgramTo run the program, choose Debug, Start Without Debugging, or press Ctrl+F5. You will seea dialog box, as shown in Figure L l8(a). Click IZes to continue. You will see the output is dis-played in a DOS window, as shown in Figure l.l8(b).

@'!ti3 pojcct b uf of data:

*u.ld ycr *c to h.{d t?i--l! !6 il ilg t CrEd Iry-

l- Don**w$*a*g.g*r l

(a)

Frcunr l.l8 The output is displayed in a DOS window.

-€ NoteThe Run command invokes the Compile command if the program is not compiled or was modified after the last comoilation.

compile and run

Page 21: Introduction to Programming with C++ Comprehensive Version chapter 1

g NoteEach project can have only one file that contains a main function. lf ;ou need to create another

file with a main function, you have two options:

I Remove the current file that contains a main function from the project by choosing

Remoue from the context menu of the program. as shown in Figure 1.19. (Note that you

can add an existing file to the project by choosing file. Add fxisting ltem.)

I Create a new poject for the new program.

Ftcunr l. I 9 You can remove a file from a project.

l.l0 Developing C++ Programs Using Dev-C++ 4l

one main function

http://www.bloodshed.net/dev/

But Dev-C++ is simpler and

l.l0 Developing C++ Programs Using Dev-C++Dev-C++ is a free C++ IDE, which can be downloaded fromdevcpp.htrnl. Visual C+t is much more powerful than Dev-C++.easier than Visual C++ for new IDE users.

l.l0.l Getting Started with Dev-C++Dev-C++ is easy to install. If you need help on installation, please refer to Dev-C++ Tutorialin the supplements.

Suppose you have installed Dev-C++. You can launch Dev-C++ from Windows Start but-ton by choosing AII Programs, Bloodshed Dev-C++, Dev-C++. The Dev-C++ user interfaceappears, as shown in Figure 1.20.

ia 1L*,s.Ifr#t,=,gl

Page 22: Introduction to Programming with C++ Comprehensive Version chapter 1

42 Chapter I Introduction to Computers, Programs, and C++

Flcunr 1.20 The Dev-C++ user interface is a single window that performs functions forediting, compiling, debugging, and running programs.

1.10.2 Creating a ProgramTo create a C++ program in Dev-C++, follow the steps here:

l. Choose File, New, Source File, an untitled file appears in the content pane, as shown inFigure 1.21.

ContentPane

,H',oifrF&i rf ;i,.ilE 1'g -&r-

h I # ".G*J,;1. r: .. :'i

2. Type in the code exactly from Listing 1.1 in the content pane, as shown in Figuret.22.

Frcunr 1.2 | The conrents of the file are displayed in the content pane.

Page 23: Introduction to Programming with C++ Comprehensive Version chapter 1

l.f 0 Developing C+r Programs Using Dev-C+r 43

FrcuRf 1.22 The code is entered in the content pane.

3. Choose File, Save to display the Save File dialog box, as shown in Figure 1.23.

Enter l.lel come. cpp in the File name field and click Scve to save the file intoWel come. cpp. (Note: you may change the directory in the Save in field to save the

file in any directory.)

Frcurc 1.23 You may save the file in any directory.

4. After you save the file, you will see the Welcome.cpp tab appear in the content pane, as

shown in Figure 1.24.

*include <iostrearR>

Lnt nain{}{

// Oisplay fiP-lco',e to C++ to ttre conso.lestd::cout << "l{elc@e to c++!i << std::endl;lrturn 0;

Page 24: Introduction to Programming with C++ Comprehensive Version chapter 1

f .f 0 Developing C+r Programs Using Dev-C+r 45

FrcuRE t.26 The compilation status is displayed.

FrcuRE 1.27 The statement system("PAUSE") is added.

Recompile and run the program. You will see the command window displayed, as shown

in Figure 1.28.

FrcuRE 1.28 The command window displays the console output-

TipYou may compile and run the prognm using one command by choosing Execute. Compile GRun, or pressing f9, or clicking the Compile e' Run toolbar button ( ffi ).

Notelf you have multiple programs in the content pane, choose the one 1ou want to run from the file

tab and use the Compile €' Run command to run the selected program.

compile and run

*incl.uce <loscreatr'l>

{// Display lteTcome to c++ ta the consoTestd::cout << "Welcone to C++!n << std::endl;

multiple programs

Page 25: Introduction to Programming with C++ Comprehensive Version chapter 1

46 Chapter I Introduction to Computers. programs, and C++

l- | | Developing c+r Programs from command Lineon Windo\Ms

DOS commands

compilers

@ xoteTo dwelop progGms from Wndow's command line, you need to know hov to use DOS commands.Please see Supplement l.C. "Compiling and Running C+r from the Command Windov,'on how touse basic DOS commands. All the supplements are accessible from the Companion Website.

when you install Dev-c++ in the previous section, a popular compiler,known as the GNUc++ compiler, is automatically installed in c : \dev-.pp\Lt n\s**.

"*". GNU is an organ_ization devoted to develop open source software (see www-gnu.org). To use the "o*iil",directly from the command line, you have to add c:\dev-ipp\bin into pATH.nniron_ment variable. Here are the steps to add the new paths in Windows 2000 and Windows Xp:

l. Choose Systems from the Window's Control Panel to display the Systems propertiesdialog, as shown in Figure 1.29(a).

2. Choose the Advanced tab and click Environment Vaiable.r to display the EnvironmentVariables dialog as shown in Figure 1.29(bl.

FrcuR: t.29 You need to add compilers in the environment path.

text editor

g++ compiler

3. choose Path in the System variable section and click Edit toadd the paths.

You can use any text editor to create and edit a c++ source code file. Figure 1.30 showshow to use the NotePad to create and edit the source code file.

To compile welcome.cpp using the GNU c++ compiler, type the command g++l{elcole.cpp -o t{elcore, as shown in Figure l.3l.If there are no rynt* errors, an exe-cutable file named welcorne.exe is created. you can run it by typing r{elcooe.

Page 26: Introduction to Programming with C++ Comprehensive Version chapter 1

<iostream>

nt mainot' // o'rsp'lay wel.cdne to C++ to the console

ita::cbut'<< "welcoare to ct+!" << std::endl;

system("PAUSE");

return 0;

Frcune|.30YoucancreateaC++sourcefileusingWindowsNotePad.

GNU C++compiler

Run

l.l2 Developing C++ Programs on UNIX 47

UNIX commands

compilers

FtcuRE 1.3 | You can compile using the GNU C++ compiler'

l.l2 Developing C++ Programs on UNIX

NoteTo develop programs on uNlx, you need to know how to use UNIX commonds. Please see

Supplement i.O, "Compitlng and Running C+r kom UNIX" on how to use basic UNIX commands'

By default, a GNU C++ compiler is automatically installed on UNIX' You can use the

vi or emacs editor to create a C++ source code file. Figure 1.32(a) shows how to use the

vi editor to create and edit the source code file named Welcome.cpp (using the command

vi Welcome.cpp).

FrcuRE l.3z (a) you can create a C++ source file using the vi editor. O) You can compile a C++ source file using the

GNU compiler.

*iaclude <iostleaa>

int rcinot

// oispLay lfelcoe to c# to thc conlolcrtd::$ut <<'ttclcre to eF+ti << std::cndl;rcturn O;

I S+-t lilel-eone.cPP -o MainS ./uainWelcme to C# !

$l

Page 27: Introduction to Programming with C++ Comprehensive Version chapter 1

48 Chapter I

GNU compiler

Introduction to Computers, programs, and C++

To compile welcome-cpp using the GNU compiler, wpethe command g++ r{ercooe.cpp-o lfain, as shown in Figure 1.32(b).If there are no syntax errors, an executable hle namedIrfain is created. You can run it by ryping ./Aain, as shown in Figure 1.32(b).

Kry TrRusassembly language 7binary numbers l0bit 5

block 14

byte 5Dev-C++ 23cable modem 7central processing unit (CpU) 4comment 14

compiler 8

dot pitch 7DSL (digital subscriber line) 7g++ command 28, 30hardware 4hexadecimal numbers l0high-level programming language g

Integrated Development Environment(rDE) 16

CHeprrn Suvnaany

keyword (or reserved word)machine language jmain function 14memory 5modem 7network interface card (NIC)operating system (OS) g

pixel 7resolution 7software 4source code l6source file l6storage devices 6statement 14

statementterminator 14stream insertion operator 14VisualC++ l7

l5

t A computer is an electronic device that stores and processes data. A computerincludes both hardware and software. In generar, hardware is the physicar aspect ofthe computer that can be seen, and software is the set of invisible instructions that con-trol the hardware and make it perform tasks.

r Computer programs, known as software, are instructions to the computer. you tell acomputer what to do through programs. computer programming consists of writinginstructions for computers to perform.

I llte machine language is a set of primitive instructions built into every computer.Assembly language is a low-level programming ranguage in which u o,n",noni" i,used to represent each of the machine-language instructions.

I High-level languages are English-like and easy to learn and program. There are overone hundred high-level languages. A program written in a trigh-tevel language i:;cailed a soarce program. since a computer cannot understand a source program, a pro_gram called a cotnpiler is used to translate the source program into a machine lan-guage program, which is then linked with other supporting library code to form anexecutable file.

I The operating system (oS) is a program that manages and controls a computer,s activ-ities' Application programs, such as Web browsers and word processors, cannot runwithout an operating system.

Page 28: Introduction to Programming with C++ Comprehensive Version chapter 1

Review Questions 49

I C+t' is an extension of C, developed by Bjarne Stroustrup at Bell [,abs during

1983-1985. C++ added a numberof features that improved the C language. Most impor-

tantly, it added the support of using classes for object-oriented programming.

! C++ source files end with the .cpp extension. You can develop C++ applications fromthe command line or using an IDE such as Visual C++ and Dev-C++.

r Every C+r program is executed from a main function. A function is a construct that

contains statements.

Rrvrrw QursnoNs-'$ Note

Answers to review questions are on the Companion Website at www.cs.armstrong.edu/liang/cpp.

Sections 1.2-1.4

l. I Define hardware and software.

1.2 Define machine language, assembly language, and highJevel programming lan-

guage.

1.3 What is an operating system?

Section 1.5 Number Systems

1.4 Convert the following decimal numbers into hexadecimal and binary numbers:

100; 4340; 2000

1.5 Convert the following binary numbers into hexadecimal numbers and decimalnumbers:

1000011001; 100000000; 10011-1

1.6 Convert the following hexdecimal numbers into binary and decimal numbers:

FEFA9; 93; 2000

Sections 1.6-1.12

1.7 Describe the history of C++. Can C++ run on any machine? What is needed tocompile and run C++ programs?

1.8 What are the input and output of a C++ compiler?

1.9 List some C++ development tools. Are tools like Visual C+r and Dev-C+r differ-ent languages frorn C++, or are they dialects or extensions of C++?

l. | 0 What is the relationship between C, C++, Java" and C#?

l.l I Explain the C++ keywords. List some C+r keywords you learned in this chapter.

l.l2 Is C++ case-sensitive? What is the case for C++ keywords?

l. | 3 What is the C+r source filename extension. and what is the C++ executable file-name extension on Windows?

l.l4 What is a comment? What is the syntax for a comment in C++? Is the commentignored by the compiler?

l.l5 What is the statement to display a string on the console?

Page 29: Introduction to Programming with C++ Comprehensive Version chapter 1

50 Chapter I Introduction to Computers, Programs, and C+r

l. | 6 Identify and fix rhe errors in the following code:

1 include <iostream>2

3 int main4{5 // Display lrlelcome to C++ to the console6 std: : cout << ',Wel come to C++ !

,' << std: : end.l ;7 return 0;8]

l.lT what is the command to compile a C++ program using the GNU compiler? whatis the command to run a C++ application on Windows and on UNIX?

Pnoc nanaMrNc Exrnclsrsl. | (Displaying a pattern) Write a C++ program that displays the following panern:

cccc

ccccc

?

++++++++++

++

++

+++++++++++