Introduction To Programming With C++ Comprehensive Version Chapter 1
Introduction To Programming With C++ Comprehensive Version Chapter 1
Introduction To Programming With C++ Comprehensive Version Chapter 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
Chapter 2
Primitive Data Types and Operations
Chapter 3
Selection Statements
Chapter 4
Loops
Chapter 5
Functions
*;1r
)':.'i:
+:
Chapter'6
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.
19:
und
Op"r1gl
Chapter 5 Functions
-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
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.
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
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
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
tl YY
2000
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
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
R2,
R3
26
Chapter
assembler
Frcuna
1.3
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
extension.exe.
G I sour""
t--_--jl
Fite
,,
Compiler
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.
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
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.
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.1
binary to decimal
bnx2n *
bn-
Binary
l0
1000
Formula
Decimal
2
8
1010101I
t7l
decimal tobinary
Toconvertadecimalnumberdtoabinarynumberistofindthebits bn,bn-1,bn-2,...,b2,
by
/. 1
--3
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
30
Chapter
1.5.2
hex to
decimal
ft6
160
Hexadecimal
7F FFFF 431
decinul to
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
+ 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
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.
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
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
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
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
Lrsrr.rc l. l_ finclude
2 3
<iostream>
int
{
maino
4
5
//
output
successful return
6
1
std::cout <<
Display Welcome
to
"Welcome
C++
to the console
8 9
return 0;
Welcome
to
C++!
file
main function
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
*/
Cycle
33
Note
You are probably wondering about such points as why the main function is declared this way
and why
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
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-
to C++!" << std::end1; to C++.NET!" << std::endl: to C++ Compiler!" << std::endl;
e]
successful return
to to to
C++!
C++.NET!
C++ Conpiler!
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
#include <iostream> int maino { ' // Display Welcome to C++ to the console std::cout << "We'lcome to C++!" << std::endl;
, return 0;
If compilation errors
flcunr
l'7
compiler command
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.
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
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
:
:
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.
36
Chapter
Frcuns
1.9
Fort sst
,,"
, . e '. Console
-.:1.
applicitton
s,fidw
*",'
.
:
a{:t'ri4Y '
'T#'
r-.:':"i. " .5.: i.
from .'ry
;,lX$'
Frcunt
l.lO
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.
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-
Gl
project
1-
E SJrce
Ees
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
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(
Whds
mr*.
rEneuver ':.. M
Frcuns
l.t2
1.9.3
project, you can create programs in the project. Here are the steps to cre:
38
Chapter
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,
:iQr-*o-;
6L|U
Rbid
Chrl
Project
OIy
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...
Ratere'EcsAdd vJeb
Re{trffi^.
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
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.
39
Ftcunr l.
3. Enter
fiom Listing
e-
GP
Sofrtix|'bookexample' boo&radrple
(t projeC)
linclude <iostrean>
:-
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
[tffit
?rlocfrr.ill $IU0l
lsEremrilros$Ast
1.9.4
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
Frcunr
l.l7
1.9.5
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).
*u.ld ycr *c
to h.{d
t?
ilg
t
l
CrEd
(a)
Frcunr
l.l8
Note
The Run command invokes the Compile command if the program is not compiled or was modi fied after the last comoilation.
l.l0
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
I I
can add an existing file to the project by choosing file. Create a new poject for the new program.
ia 1L*,s.Ifr#t,=,gl
Ftcunr l.
l.l0
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
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
Flcunr 1.20 The Dev-C++ user interface is a single window that performs functions for editing, compiling, debugging, and running programs.
Content
Pane
,H',oifrF&i
rf
;i,.ilE
r:
-&r1'g
*J,;1.
.. :'i
h # ".G
I
Frcunr
1.2
2. Type in the code exactly from Listing 1.1 in the content pane, as shown in Figure
t.22.
l.f
43
// 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
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
as
.f
Using
Dev-C+r 45
FrcuRE
t.26
*incl.uce <loscreatr'l>
{
// Display lteTcome to c++ ta the consoTe std::cout << "Welcone to C++!n << std::endl;
FrcuRE
1.27
will
FrcuRE
1.28
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 ( ).
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
l-
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
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",
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
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
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
l.l2
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
Kry TrRus
assembly
binary
language numbers l0
language
14
l5
Dev-C++
(CpU)
comment 14 compiler 8
dot pitch 7 DSL (digital subscriber line) 7 g++ command 28, 30
pixel
resolution 7 software 4
source code l6 source file l6 storage devices 6
hardware 4
hexadecimal
high-level
statement
g
14 14 14
statementterminator
stream insertion
(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
! 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.
1.2 1.3
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
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
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?
(Displaying a pattern) Write a C++ program that displays the following panern:
ccc
c c c
+
+
ccc
+++++++++ +
+
+++++++++
+