Anda di halaman 1dari 29

Pnnr 1

FUnUDAMENTAL$
: rt,.
,',

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.

i.,

r,

.,-':

'

,o;.i'!.,

,i

t*".;riil 'rr

'

-::,i

i:

Chapter

Introduction to Computers, Programs, and C++

Chapter 2
Primitive Data Types and Operations

Chapter 3
Selection Statements

Chapter 4
Loops

Chapter 5
Functions
*;1r

)':.'i:

+:

Chapter'6

Prerequisites for Part


basic computer skills

recursion

sorting algorithms

This book does not require any prior programming experience, nor any mathematics, other than elementary high school algebra and basic computer skills such as using Windows, 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 l8 introduces 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

-1

CTnPTER

:'.,:.

.,,'

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

:,,

Objectives r 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).
I I I
(Optional) To develop C+r using Visual C++ ($1.9). (Optional) To develop C+r using Dev-C+r ($1.10). (Optional) To develop on Windows ($l.ll). (Optional) To develop on Unix ($1.12).

C+r using command line tools C+r using command line tools

g"

22

Chapter

Introduction to Computers, Programs, and C++

l.

I lntroduction

You use word processors to write documents, Web browsers to explore the Internet, and email programs to send email over the Internet. Word processors, browsers, and email programs are all examples of software that runs on computers. Software is developed using programming Ianguages. C+r is a popular and powerful programming language. Most application software such as word processors, browsers, and email progams are developed using C+r. This book will 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 are familiar with such terms as CPU, memory disks, operating systems, and programming languages. You may also skip $1.5 and use it as reference when you have questions regarding binary and hexadecimal numbers.

1.2 What ls a Computer?


A computer is an electronic device that stores and processes data. A computer includes both
hardware software

hardware and software. In general, hardware is the physical aspect of the computer that can be seen, and software is the invisible instructions that control the hardware and make it perform specific tasks. Computef programming consists of writing instructions for computers to 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 you

do. This section gives a brief introduction to computer hardware components and their functionality. A computer consists of the following major hardware components, as shown in Figure l. L

r I I I I

Central Processing Unit (CPU)

Memory (main memory)


Storage Devices (disks, CDs, tapes)

Input and Output Devices (monitors, keyboards, mice, printers) Communication Devices (modems and network interface cards (NICs))

nput
Devices
e.g., Disk, CD, and Tape e.g.,

I
I

Devices
.g.,

output I
I

Modem,

e.g ., Keyboard

Monitor

and NIC

Mouse

Printer

A computer consists of CPU, memory hard disk, floppy disk, monitor, printer, and communication devices.
Ftcunt
The components are connected through a subsystem called a Dns that transfers data between the components.

l.l

1.2.1 Central
CPU

Processing Unit

The central processing unit (CPA is the brain of a computer. It retrieves instructions from memory 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

1.2 What ls a Computer? 23


components. The arithmetic and logic unit performs numeric operations (addition, subtraction, 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 synchronize 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. If you buy a PC now, you can get an Intel Pentium 4 Processor at3 gigahenz (GHz) (l GHz is
1000 MHz).

speed

hertz
megahertz

gigahertz

1.2.2 Memory
Computers 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 content

tl YY

2000

01001010 01100001 01110110 01100001 00000011

Encoding for character'J' Encoding for character 'a' Encoding for character'v' Encoding for character 'a' Encoding for number 3

zmL 2ffi2
2003

2W

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 popular 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 memory byte is never empty, but its initial content may be meaningless to your Program. The current 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 to as 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 their surface. Compared to the CPU chips, memory chips are less complicated, slower, and less
expensive.

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

of

numeric keypad

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

move

anow key

The Insert, delete, page up, and, page down keys, located above the arrow keys, are used in word 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 around
the screen or to click on an object on the screen to trigger it to respond.

The Monitor
The monitor displays information (text and graphics). The resolution and dot pitch determine the quality of the display. The resolution specifies the number of pixels per squiue inch. Pixels (short for "picture scrcen resolurion elements") are tiny dots that form an image on the screen. A common resolution for a l7-inch screen, for example, is 1024 pixels wide and 768 pixels high. The resolution can be set manually. 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 pitch 0.81 millimeters. The smaller the dor pitch, the better the display.

1.2.5

Communication Devices

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

modem

DsL
NIC

LAN
mbps

1.3 Programs
as software, are instructions to the computer. You tell a computer what to do through programs. without programs, a computer is an empty machine. computers do not understand human languages, so you need to use computer languages to communi-

Computerprogrcns, known

sofrware

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 language languages are different for different types of computers. The instructions are in the form of binary code, so you have to enter binary codes for various instructions. Programming using a native machine language is a tedious process. Moreover, the programs are highly difficult to read and modify. For example, to add two numbers, you might have to write an instruction in

binary like this: 1101101010011010


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

R2,

R3

26

Chapter

lntroduction to Computers, Programs, and C++


Assembly languages were developed to make programming easy. Since the computer cannot undentand assembly language, however, a program called assembler is used to convert assembly language programs into machine code, as shown in Figure 1.3.

assembler

Frcuna

1.3

Assembler translates assembly language instructions to machine code.

high-level language

Since assembly language is machine-dependent, an assembly program can only be executed on a particular machine. Assembly programs are written in terms of machine instructions with easy-to-remember mnemonic names. The high-level languages were developed in order 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 example, 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

source program

compiler

applications and is used primarily for business data processing. FORTRAN was designed for mathematical 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 developing graphical user intertaces and in rapid application development. C combines the power of an assembly language with the ease of use and portability of a high-level language. C+r is popular for system software projects like writing compilers and operating systems. The Microsoft Windows operating system was coded using C+r. Java, developed by Sun Microsystems, is widely used for developing Internet applications. C# (pronounced C sharp) is a new language developed 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 computer cannot understand a source program, a program called a compiler is used to translate the

1.4 Operating Systems 27


source program into a machine-language program. The machine-language program is often then linked with other supporting library code to form an executable frle. The executable file can be executed on the machine, as shown in Figure 1.4. On Windows, executable files have

extension.exe.

G I sour""

t--_--jl

Fite

,,

Compiler

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

f:-..---l

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

1.4 Operating Systems


The operating system (OS) is the most important program that runs on a computer to manage and control its activities. You are probably using Windows (98, NT, 2000, XP, or ME), Mac OS, or Linux. Wndows is currently the most popular PC operating system. Application programs, such as a Web browser or a word processol cannot run without an operating system. The interrelationship 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 r r

Controlling and monitoring system activities Allocating and assigning system resources
Scheduling operations

1.4.1 Controlling and Monitoring

System Activities

Operating systems are responsible for security, ensuring that unauthorized users do not access the system. Operating systems perform basic tasks, such as recognizing input from the keyboard, sending output to the monitor, keeping track of files and directories on the disk, and controlling peripheral devices, such as disk drives and printers. Operating systems also make sure that different programs and users running at the same time do not interfere with each other.

1.4.2 Allocating and Assigning


program.

System Resources

The 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 the

1.5 (Optional) Number Systems 29

1.5.1

Conversions between Binary Numbers and Decimal Numbers


..

Given a binary number b,,bn-1bn-2.

b2bftg, the equivalent decimal value is

binary to decimal

bnx2n *

bn-

rxzn-t * bn-2x2n-2 + ... + b2x22 + btxzt + boxzo


Conversion

The following are examples of converting binary numbers to decimals:

Binary
l0
1000

Formula

Decimal
2
8

1010101I

tx2t+0x20 tx2t+0x22+ 0x2r+0x20 lxzT+0x26+ lx2s +0x24 + lx2t +0x22 + lx21+lxzo

t7l
decimal tobinary

Toconvertadecimalnumberdtoabinarynumberistofindthebits bn,bn-1,bn-2,...,b2,

by

and bs such that

d: bnx2n + bn-t\2n-t + bn-zx2n-2 + ... r bzx22 + b1x2r + blx20


These bits can be found by successively dividing d by 2 until the quotient is 0. The remainders are 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:

2l t/zl 7' t/rl 1l7 026143060122


1

/. 1

--3

-.'i5 --30 -/ 7 --61 l-al,.l-.---.t/ tl 1s-" tl rJ ,o/ rl 6(" zl w -

Quotient

-)

I
Y

0
+ b3

I
+
b1

Remainder

+
b6

i
I

t
bo

b5

b4

b2

Tip
The Windows Calculator, as shown in Figure 1.6, is a useful tool for performing number conversions. To run it, choose Program' Accessories, and calculator from the start button. Decimal

Binary

Frcun:

1.5

You can perform number conversions using the windows calculator.

30

Chapter

Introduction to Computers, Programs, and C+r

1.5.2
hex to

Conversions between Hexadecimal Numbers and Decimal Numbers


. . h2h1hg, the

decimal

Given a hexadecimal number hnhr-1hn-2.

equivalent decimal value is

hnx l6n r hn_tx l6n-l

* hr_zx 16"-2 + ... + h2x 162 + hx16l

ft6

160

The following are examples of converting hexadecimal numbers to decimals:

Hexadecimal

7F FFFF 431
decinul to

Formula 7xl6r+15x160 15x163+15x162+15xl6t+15x160 4x162+3x16l+lx160


Conversion

Decimal

t27
65535

lo73

hex
hn,

To convert a decimal number d to a hexadecimal number is to find the hexadecimal disits 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

160

by 16 until the quotient is 0. The remainders 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
These numbers can be found by successively dividing d

follows:

l--7l-r23 -''19 r9
0
7 tt VY ht
tt2

,/

Quotient

1,1
ho

Remainder

1.5.3
hex to binary

Conversions between Binary Numbers and Hexadecimal Numbers

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

Forexample,thehexadecimalnumberTBisllll0ll,whereTislllinbinary,andBis l0l I in binary.


binary to hex

To convert a binary number to a hexadecimal, convert every four binary digits from right to a hexadecimal number. For example, the binary number 1l 10001l0l is 38D, since I l0l is D, 1000 is 8, and I I is 3, as shown below

left in the binary number into

1r1000 1101
tl
I

38

&

Note
Octal numbers are also useful. The octal number system has eight digits, 0 to ber 8 is represented as l0 in the octal system.
7.

A decimal num-

1.6 History of
Taau
0
t I

C++

3|

l.l

Converting Hexadecimal to Binary Binary


0

Hexadecimal

Decimal
0

I
t0
2 J
A

2
3

ll
100

4
5

l0l
110

6
7 8

6
7
8

lll
1000
1001

A
B

1010

l0

l0l l
I 100 I

ll
t2

c
D
E

t0l

l3
t4

1ilO

llll

l5

1.6 History of C++


C, C++, Java, and C# are very similar and related. C++ evolved from C. Java was modeled after C++. C# is a subset of C++ with some features similar to Java. If you know one of these languages, it is easy to learn the others. C evolved from the B language and the B language evolved from the BCPL language. BCPL was 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 create early versions of the UNX operating system at Bell l,aboratories in 1970 on a DEC PDp-7 computer. 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 the responsibility of the programmer. Dennis Ritchie extended the B language by adding types and
other 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. added a number of features that improved the C language. Most importantly, it added the support of using classes for object-oriented programming. Object-oriented programming can

c
C++

C+r

make programs easy to develop and easy to maintain. C++ could be considered a superset of C. The features of C are supported by C++. C programs can be compiled using C++ compilers. 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 tnstitute (ANSI) in 1998. The AN,S/ sta ndard is an attempt to ensure that C++ is portable, i.e., your programs compiled using one vendor's compiler can be compiled without errors from any other vendors on any platform. Since the standard has been around for a while, all the major vendors now support the ANSI standard. Nevertheless, the C++ compiler vendors may add proprietary features into the compiler. So, it is possible that your program may compile fine by one compiler, but have to modify the code in order to be compiled by a different compiler.
ANSI standard

32

Chapter

Introduction to Computers, Programs, and C+r

1.7 A Simple C++ Program


Let us begin with a simple C+r program that displays the message "Welcome to C+r!" on the console. The program is shown in Listing 1.1.

include library main function comment

Lrsrr.rc l. l_ finclude
2 3

Wel come. cpp

<iostream>

int
{

maino

4
5

//

output
successful return

6
1

std::cout <<

Display Welcome

to

"Welcome

to C++!" << std::end1;

C++

to the console

8 9

return 0;

Welcome

to

C++!

line number directive


header

file

main function

console output stream insertion operator

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 this program, which is needed to support console input and output. The library like iostream is called 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 contains statements. The mainfunction defrned in lines 3-9 contains two statements. The statemnts are enclosed 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 output. The << oprator, referred to as the stream insertion operator, sends a string to the console. A string must be enclosed in quotation marks. The statement in line 6 first outputs the string "welcome 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 that the output is displayed immediately. What is std? std stands for standard name space. std: : is placed in front of cout and endl to denote that cout and endl are in the standard name space. The statement in line 8

std

return
successful exit comment

0;

is placed at the end of every main function to exit the program. The value 0 indicates that the program has terminated successfully. Line 5 is a comment that documents what the program is and how the program is constructed. Comments help programmers to communicate and understand the program. Com-

line comment
paragraph r'onrment

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 enclosed between /'r and'1'/ on one or several lines, called a paragraph co,rtment. When the compiler sees / / , it ignores all text after / / on the same line. When it sees /':', it scans for the next '',1 and ignores any text between /r, and" /. Here are examples of the two types of comments:

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

C++l

C++l

*/

1.8 C++ Program Development


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 return in this program.

Cycle

33

Note
You 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

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 commessage to the console. Your questions cannot be

ing chapters.

Note
Like any other programming language,

obeys

the

synlax rules. The C++ compiler

C+r has its own syntax. and you need to write code that 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 function ends with a semicolon (; ).

Caution
C++ source programs are cose-sensiliue. lt would be wrong, for example, to replace main in program with Mai n.

the

case-sensitive

The program in Listing l. I displays one message. Once you understand the program, it is easy 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.

3{ 4 std::cout 5 std::cout 6 std::cout 8 return 0;


7

Ltsrrruc 1.2 Wel come1. cpp 1 #include <iostream> 2 int maino


<< "Welcome << "Welcome << "Welcome

include library main function output

to C++!" << std::end1; to C++.NET!" << std::endl: to C++ Compiler!" << std::endl;

e]

successful return

Welcome Welcome Welcome

to to to

C++!

C++.NET!

C++ Conpiler!

1.8 C++ Program Development Cycle


You 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 ltx them by modifying the program, and then recompile it. If your pro$am has runtime errors or does not produce the correct result, you have to modify the program, recompile it, and execute

it again.

Note

A C++ source file Wpically ends with the extension .cpp. Some compilers may accept other name extensions (e.g., .c, .cp, or .c). but you should stick with the .cpp ecension to be compliant with all ANSI C+r compilers.

file

.cpp source

file

34

Chapter

lntroduction to Computers, programs, and C++

Source code (developed by the

#include <iostream> int maino { ' // Display Welcome to C++ to the console std::cout << "We'lcome to C++!" << std::endl;

Saved on the disk

, return 0;

Stored on the disk

If compilation errors

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

Stored on the disk

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

Run Executable Code e.g., Welcome

If runtime errors or incorrect result

flcunr

l'7

linking, and executing programs.

The C++ programming-development process consists of creating/modifying source code, compiling,

compiler command

Note The c+r

example' the inc'lude statement in line I of Listing Ll is a directive to tell the compiler to include a library. The compiler then translates the source code into a machine code file called object file, and finally. it links the object file with supporting library files to form an executable file' On Windows, the object file is stored on disk with an .obj extension and the executable files are stored with an .exe extension. on uNlX, the object file has an . o extension and the executable files do not have file extensions.

compiler command performs three tasks in sequence: preprocessing. compiling. and linking. The compiler first processes the directives. The directives start with the t sign. For

IDE

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 a window, 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++.

You can develop a C++ program from a command line or from an IDE. An IDE is a software that provides an integrated development environment (lDE) for rapidly developing

C+r. The

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

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. A free version named Vsual C++ 2005 Express Edition is included in the book's Companion
CD-ROM. This section introduces how to create a project, create a program, compile, and run
the program.

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++ from the 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

1.9.t

interface appears, as shown in Figure 1.8.

sw-f! gm Id hx S H rbfErsvG*gar@demadtEl H l,ledbsh.e Hssgls St rts xA S l,lon, 0l r|ay 2006 2r:35:05 GllT The tlefi sttm il*ngs H Stdter xr b a ftty functhfrg orstom ctEt cbt tEt enabts S lou 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 )orr
Anmfifug
the Upgrade

Ysr Gam

Ar@de r,lxh'nre

fre Tue, 16 Hay 2006 15:43:21 Gt{T - Chck c|n devb9s hil$g resdirce that tedr !dr, stePby-step, to develop )air own r6d gEfrEs oo SE Pc' and ents to wh a

tte

DffifoadttE PSD(

lilh.ts t{s n
Geafq drd

orn 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

:
:

\/lsud C++ l.|anaoirg \b.d...

mi*.

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

1.9.2

Creating a Project

To 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 the Templates column. Type bookexampl e in the Name field and c : \smi th in the Location freld. Click OK to display the Win32 Application Wizard window, as shown in
Figure 1.10.

3. Click Ne# to display the application settings window,

as shown in Figure 1.11.

36

Chapter

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

:F,"1..., .The{ lrr lho orrant


Apgliation Setungs
. .'.1

Fort sst

,,"

, . e '. Console
-.:1.

applicitton
s,fidw

*",'
.
:

a{:t'ri4Y '

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

": Cld fr|iih

from .'ry

!o acce$ th. a,rr8nt setffe

;,lX$'

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 in the Additional options section. Click Finish to create a project. You will see the project
named bookexampl e in the solution explorer, as shown in Figure 1.12.

1.9 Developing C+r Programs Using Visual

C+r 37

Important check it

Frcune

l.l

Win32 Application Settings window lets you set the application type.

Solution
explorer shows the files in the

#e@tr E
i-

lteaOer nes Rescurce Fles

Gl

project

1-

E SJrce

Ees

Announcirq tlrc Upgrade Your caole Arcade Machirre

Sw.,.]l

Tue, 16 May 2006 16:43:21 GMT - Chck out these free garne rt l devdoper harrmg resourG that tdr )/ou, stepby-step, U'l to devdop your own arcade games on ttre rc, and mter to win a fiil

tr*r

Hs PenaryGabga arcade

tledasharc Messerer Starter


llon,

rnad|]|e! Kit

F"l

Opetr: Oate

ttoJed...
ProFct...

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.
Interfdce, )lou crn start o(prinentiE wilh robotics ard fron your rc, aJtofiEtialy arilnd obctades, and pbry
.NET

May 2006 2r :36;05 Girr - Th trtedia share l.lesserger sarter lG b a fuly furEtixirg orstom chat that enables ).ar to send irslant messages to )roer frtsnds and even your must colectbn lridr tlsn over a bcd area network (tAN). '

ol

share H

hl ffi bl
'.

Dortr{oad th PSDI(

coertsd yorir robot ...

Whds

h \lHrd C++ crafixg and llan4,hg vlgrd


l{erY

mr*.

rEneuver ':.. M

Frcuns

l.t2

A project is created for C++ console applications.

1.9.3

Creating a C++ Program


a

After you created

project, you can create programs in the project. Here are the steps to cre:

ate a C++ program for L,isting l. I

38

Chapter

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.

i5l,:El-.Ef.El-,f,

:-F-t 5'_-11 );octrg t \rfirl2

:iQr-*o-;

6L|U

Rbid

Chrl
Project

OIy

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 SJ b dvebg 161tr oern rcadc ailn6 on UE rc, md ffts to m a $-l

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

ard

ordr...

iGhorvc&98d6(,rEdnd t'tnfRshile }ksrrgtr stdtd Kt

Ratere'EcsAdd vJeb

Re{trffi^.

Set6 st3tlrp Projct

Debrg

n b a n-ry turctirrE crEto.n ciat tu that mbts Tl-t Ie! send irstanl rt$gs b )ur ffi ild wen stBre El fn -- |ru*ohcurfihdmwrabcdneantnort(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, H pbot? 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 pbynirc -!| f*t lh Aprl20fi, DitrlX SOX
ifon, Ol l{av 2006 2r:35:43 GHT - ltis S0( tldnts tfr. toob neded to buld ottng-edge, md*rEh, rtractvc a9d6ttIi

Hon,-Or tEy 2006 2r:36:05 C'HT - Thc llQdb StUe

r.rcerae $ |

{|

I.l

,Pa----*_
Y9f""L
Prop6tis
"

(;erti.rg ttnrtrd witlt \/Ardl Cr. I rpra$ fdibn TE, 07 l'lar 2006 01 :28:17 C+tf - Dsff t s C++ txF63 Edtit taturer, provir6 a Oiitd lil ild a Hqr-dd sE r :J

Frcum

l.l3

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

Viglal C++

iUl
:

iftr
- Data - PropertFhets

FtcuRr

l.l4

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

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 in
the l,ocation freld. Click
A

39

dd to create the file, as shown in Figure I . 15.

Ftcunr l.

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.

e-

GP

Sofrtix|'bookexample' boo&radrple

(t projeC)

linclude <iostrean>

AneaOernes nesoureFes E- E SourceFs

:-

r' f

lint
| I I

araino

Ir

- w*nr.cpp

// oisptay flelcone to c.|+ to the std::cout << 'l{elccEle to c++!i << returtr 0;

L'

6eT
,

FtcuRE

l.l6

The source code for Welcome.cpp is entered.

[tffit

?rlocfrr.ill $IU0l

lsEremrilros$Ast

1.9.4

Compiling a C++ Program

After 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.

40 Chapter

Introduction to Computers, Programs, and C++

Frcunr

l.l7

Choose the Compile command to compile the prograrn.

1.9.5

Running a C++ Program

To run the program, choose Debug, Start Without Debugging, or press Ctrl+F5. You will see a dialog box, as shown in Figure L l8(a). Click IZes to continue. You will see the output is displayed 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 ryl- Don**w$*a*g.g*r

ilg

t
l

CrEd

(a)

Frcunr

l.l8

The output is displayed in a DOS window.

compile and run

Note
The Run command invokes the Compile command if the program is not compiled or was modi fied after the last comoilation.

l.l0

Developing C++ Programs Using Dev-C++

4l

Note
Each project can have only one file that contains a main function. lf file with a main function, you have two options:

;ou

need to create another

one main function

I I

Remove the current

file that contains a main function from the project by choosing


in Figure 1.19. (Note that you

Remoue from the context menu of the program. as shown

can add an existing file to the project by choosing file. Create a new poject for the new program.

Add fxisting ltem.)

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

Ftcunr l.

You can remove a file from a project.

l.l0

Developing C++ Programs Using Dev-C++

Dev-C++ is a free C++ IDE, which can be downloaded from http://www.bloodshed.net/dev/ devcpp.htrnl. Visual C+t is much more powerful than Dev-C++. But Dev-C++ is simpler and 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++ Tutorial in the supplements. Suppose you have installed Dev-C++. You can launch Dev-C++ from Windows Start button by choosing AII Programs, Bloodshed Dev-C++, Dev-C++. The Dev-C++ user interface appears, as shown in Figure 1.20.

42

Chapter

Introduction to Computers, Programs, and C++

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

1.10.2 Creating a Program


To create a C++ program in Dev-C++, follow the steps here:

l. Choose File, New, Source


Figure 1.21.

File, an untitled file appears in the content pane, as shown in

Content
Pane

,H',oifrF&i

rf

;i,.ilE
r:

-&r1'g

*J,;1.

.. :'i

h # ".G
I

Frcunr

1.2

The conrents of the file are displayed in the content pane.

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

l.f

0 Developing C+r Programs Using Dev-C+r

43

*include <iostrearR> Lnt nain{}


{

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

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 into Wel 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.


see the

4. After you save the file, you will


shown in Figure 1.24.

Welcome.cpp tab appear in the content pane,

as

.f

0 Developing C+r Programs

Using

Dev-C+r 45

FrcuRE

t.26

The compilation status is displayed.

*incl.uce <loscreatr'l>
{

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

FrcuRE

1.27

The statement system("PAUSE") is added.

Recompile and run the program. You in Figure 1.28.

will

see the command window displayed, as shown

FrcuRE

1.28

The command window displays the console output-

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

compile and run

ffi

Note
lf 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.

multiple programs

46 Chapter

Introduction to Computers. programs, and C++

l-

Developing c+r Programs from command Line on Windo\Ms

DOS commands

xote
To dwelop progGms from
Please see Supplement

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

compilers

when you install Dev-c++ in the previous section,

c++ 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 directly from the command line, you have to add c:\dev-ipp\bin into pATH.nniron_ "o*iil",

popular compiler,known as the GNU

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 properties dialog, as shown in Figure 1.29(a).
the Advanced tab and click Environment Vaiable.r to display the Environment Variables dialog as shown in Figure 1.29(bl.

2. Choose

FrcuR:

t.29

You need to add compilers in the environment path.

3. choose Path in the System variable section and click Edit toadd
text editor g++ compiler

the paths.

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 executable file named welcorne.exe is created. you can run it by typing r{elcooe.

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

l.l2

Developing C++ Programs on

UNIX

47

<iostream>

nt

maino
o'rsp'lay wel.cdne to C++ to the console "welcoare to ct+!" << std::endl;

' //

ita::cbut'<<
return 0;

system("PAUSE");

Frcune|.30YoucancreateaC++sourcefileusingWindowsNotePad.

GNU C++
compiler
Run

FtcuRE 1.3

You can compile using the GNU C++ compiler'

l.l2

Developing C++ Programs on UNIX


UNIX commands

Note

commonds. Please see To develop programs on uNlx, you need to know how to use UNIX UNIX commands' basic use how to on Supplement i.O, "Compitlng and Running C+r kom UNIX"

You can use the By default, a GNU C++ compiler is automatically installed on UNIX' 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).

compilers

*iaclude <iostleaa>

int rcino
t

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

Welcme to C#

S ./uain

S+-t lilel-eone.cPP
!

-o Main

$l

FrcuRE

l.3z

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

GNU compiler.

48 Chapter
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 named Irfain is created. You can run it by ryping ./Aain, as shown in Figure 1.32(b).

Kry TrRus
assembly

binary

bit 5 block 14 byte 5

language numbers l0

keyword (or reserved word)


machine

language
14

l5

Dev-C++

main function memory 5 modem 7


23

cable modem 7 central processing unit

(CpU)

comment 14 compiler 8
dot pitch 7 DSL (digital subscriber line) 7 g++ command 28, 30

pixel

network interface card (NIC) operating system (OS) g


7

resolution 7 software 4
source code l6 source file l6 storage devices 6

hardware 4
hexadecimal

high-level

numbers l0 programming language


16

statement
g

14 14 14

statementterminator
stream insertion

Integrated Development Environment

(rDE)

operator VisualC++ l7

CHeprrn Suvnaany
t
A
the computer that can be seen, and software is the set of invisible instructions that control the hardware and make it perform tasks.

computer is an electronic device that stores and processes data. A computer includes both hardware and software. In generar, hardware is the physicar
aspect

of

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

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.
High-level languages are English-like and easy to learn and program. There are over one hundred high-level languages. A program written in a trigh-tevel language i:;

llte

machine language

executable file.

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 language program, which is then linked with other supporting library code to form
an

The operating system (oS) is a program that manages and controls a computer,s activities' Application programs, such as Web browsers and word processors, cannot run without an operating system.

Review

Questions 49

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 importantly, it added the support of using classes for object-oriented programming.

! r

C++ source files end with the .cpp extension. You can develop C++ applications from the command line or using an IDE such as Visual C++ and Dev-C++. 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 1.3

Define machine language, assembly language, and highJevel programming language.

What is an operating system?

Section 1.5 Number Systems

1.4 1.5

Convert the following decimal numbers into hexadecimal and binary numbers:

100; 4340;
numbers:

2000

Convert the following binary numbers into hexadecimal numbers and decimal

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 1.8 1.9 0 l.l I l.l2 l. | 3


l.
|

Describe the history of C++. Can C++ run on any machine? What is needed to compile and run C++ programs? What are the input and output of a C++ compiler?

List some C++ development tools. Are tools like Visual C+r and Dev-C+r different languages frorn C++, or are they dialects or extensions of C++?
What is the relationship between C, C++, Java" and C#? Explain the C++ keywords. List some C+r keywords you learned in this chapter. Is C++ case-sensitive? What is the case for C++ keywords? What is the C+r source filename extension. and what is the C++ executable filename extension on Windows? What is a comment? What is the syntax for a comment in C++? Is the comment ignored by the compiler? What is the statement to display a string on the console?

l.l4 l.l5

50

Chapter

Introduction to Computers, Programs, and C+r


l.
|

Identify and fix rhe errors in the following code:

1 include <iostream> 3 int main 4{ 5 // Display lrlelcome to C++ to the console 6 std: : cout << ',Wel come to C++ ! ,' << std: : end.l ; 7 return 0; 8]
2

l.lT

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

Pnoc nanaMrNc Exrnclsrs


l.

(Displaying a pattern) Write a C++ program that displays the following panern:

ccc
c c c

+
+

ccc

+++++++++ +
+

+++++++++
+