Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 27

Overview of Computers and Programming

CHAPTER OBJECTIVES
To learn about the different categories of computers To understand the role of each component in a computer To understand the purpose of an operating system To learn the differences between machine language, assembly language, and higher level languages To understand what processes are required to run a C program To learn how to solve a programming problem in a careful, disciplined way To understand and appreciate ethical issues related to the use of computers and programming

U IT

Introdu!tion

Computers are machines which essential! without a list of instructions to follow, the computer is virtually useless" , and output information can #rogramming languages allow us to write those programs and thus to communicate with computers" with data of all kinds: $ou are about to begin the study of computer science using one of the most es, graphics, and sound, to versatile programming languages available today: the C language" This chapter introduces you to the computer and its components and to the ma%or categories of The computer programming languages" &t discusses how C programs are processed by a computer" &t program s role in also describes a systematic approach to solving programming problems called the this technology is software development method and shows you how to apply it"

"#"

E$e!troni! Computers T%en and ow


The first electronic computer was built in the late 1'()s by *r" +ohn ,tanasoff and Clifford -erry at &owa .tate /niversity" ,tanasoff designed his computer to assist graduate students in nuclear physics with their mathematical computations" The first large0scale, general0purpose electronic digital computer, called the 12&,C, was completed in 1'34 at the /niversity of #ennsylvania with funding from the /"." ,rmy" 5eighing () tons and occupying a ()0by06)0foot space, the 12&,C was used to compute ballistics tables, predict the weather, and make atomic energy calculations" These early computers used vacuum tubes as their basic electronic component" Technological advances in the design and manufacture of electronic components led to new generations of computers that were considerably smaller, faster, and less expensive than previous ones"

1"1 1lectronic Computers Then and 2ow

!omputer !%ip &mi!ropro!essor !%ip' a silicon chip containing the circuitry for a computer processor

/sing today s technology, the entire circuitry of a computer processor can be pack0 aged in a single electronic component called a computer or microprocessor chip 78 ig" 1 "19, which is less than one0fourth the si:e of a standard postage stamp" Their affordability and small si:e enable computer chips to be installed in watches, cellphones, ;#. systems, cameras, home appliances, automobiles, and, of course, computers" <odern computers are categori:ed according to their si:e and performance" #ersonal computers, shown in 8ig" 1"=, are used by a single person at a time" >arge real0time transaction processing systems, such as ,T<s and other banking net0 works, and corporate reservations systems for motels, airlines, and rental cars use mainframes, very powerful and reliable computers" The largest capacity and fastest computers are called supercomputers and are used by research laboratories and in computationally intensive applications such as weather forecasting"

Chapter 1 ?verview of Computers and #rogramming

(I)URE "#* 7a9 *esktop Computer, i<ac" 7@ Augh ThrelfallB,lamy9" 7b9 Aewlett #ackard >aptop" 7@ Aewlett0#ackard Company9" 7c9 i#ad" 7@ *" AurstB,lamy9" 7d9 ,ndroid phone, >; Thrill 3;" 7@ AandoutB<CTB2ewscom9"

1"= Computer Aardware

The elements of a computer system fall into two ma%or categories: hardware and software" Aardware is the equipment used to perform the necessary computations and includes the central processing unit 7C#/9, monitor, keyboard, mouse, printer, and speakers" .oftware consists of the programs that enable us to solve problems with a computer by providing it with lists of instructions to perform" #rogramming a computer has undergone significant changes over the years" &nitially, the task was very difficult, requiring programmers to write their program instructions as long binary numbers 7sequences of )s and 1s9" Aigh0level pro0 gramming languages such as C make programming much easier"

"#*

Computer Hardware
*espite significant variations in cost, si:e, and capabilities, modern computers resemble one another in many basic ways" 1ssentially, most consist of the following components: <ain memory .econdary memory, which includes storage devices such as hard disks, C*s, *D*s, and flash drives C Central processing unit C &nput devices, such as keyboards, mouses, touch pads, scanners, %oysticks C ?utput devices, such as monitors, printers, and speakers
C C

8igure 1"( shows how these components interact in a computer, with the arrows pointing in the direction of information flow" The program must first be transferred from secondary storage to main memory before it can be executed" 2ormally the person using a program 7the program user 9 must supply some data to be processed" These data are entered through an input device and are stored in the computer s main memory, where they can be accessed and manipulated by the central process0 ing unit" The results of this manipulation are then stored back in main memory" 8inally, the information in main memory can be displayed through an output device" &n the remainder of this section, we describe these components in more detail"

,emor<emory is an essential component in any computer" >et s look at what it consists of and how the computer works with it"

Chapter 1 ?verview of Computers and #rogramming

(I)URE "#. Components of a Computer


.econdary storage

&nput devices

<ain memory

?utput devices

Central processing unit

Anatomy of Memory &magine the memory of a computer as an ordered sequence of storage locations called memory cells 78ig" 1"39" To store and access information, the computer must have some way of identifying the individual memory cells" Therefore, each memory cell has a unique address that indicates its relative position in memory" 8igure 1"3 shows a computer memory consisting of 1))) memory cells with addresses ) through '''" <ost computers, however, have millions of individual memory cells, each with its own address" The data stored in a memory cell are called the contents of the cell" 1very memory cell always has some contents, although we may have no idea what they are" &n 8ig" 1"3, the contents of memory cell ( are the number =4 and the contents of memory cell 3 are the letter A" ,lthough not shown in 8ig" 1"3, a memory cell can also contain a program instruction" The ability to store programs as well as data is called the stored program concept: , program s instructions must be stored in main memory before they can be executed" 5e can change the computer s operation by stor0 ing a different program in memory"

1"= Computer Aardware


<emory ,ddress ) 1 = ( 3 Contents -27.2 354 0.005 -26 H

''E '''

X 75.62 ))1)11)) -yte

-it

(I)URE "#/ 1))) <emory Cells in <ain <emory

(I)URE "#0 Felationship -etween a -yte and a -it

bytes" , byte is the amount of storage required to store a single character, such as the letter A in memory cell 3 of 8ig" 1"3 " The number of bytes a memory cell can contain varies from computer to computer" , byte is composed of even smaller units of storage called bits 7 8ig" 1"69" The term bit, derived from the words binary digit, is the smallest element a computer can deal with" -inary refers to a number system based on two numbers, ) and 1, so a bit is either a ) or a 1" ;enerally, there are E bits to a byte"

-ytes and -its , memory cell is actually a grouping of smaller units called Storage and Retrieval of Information in Memory 1ach value in memory is represented by a particular pattern of )s and 1s" , computer can either store a value or retrieve a value" To store a value, the computer sets each bit of a selected memory cell to either ) or 1, destroying the previous contents of the cell in the process" To retrieve a value from a memory cell, the computer copies the pattern of )s and 1s stored in that cell to another storage area for processing! the copy operation does not destroy the contents of the cell whose value is retrieved" This process is the same regardless of the kind of informationGcharacter, number, or program instructionGto be stored or retrieved" <ain <emory <ain memory stores programs, data, and results" <ost computers have two types of main memory: random access memory 7F,<9, which offers

Chapter 1 ?verview of Computers and #rogramming

temporary storage of programs and data, and read0only memory 7F?<9, which stores programs or data permanently" F,< temporarily stores programs while they are being executed 7carried out9 by the computer" &t also temporarily stores such data as numbers, names, and even pictures while a program is manipulating them" F,< is usually volatile memory, which means that everything in F,< will be lost when the computer is switched off" F?<, on the other hand, stores information permanently within the computer" The computer can retrieve 7or read9, but cannot store 7or write9 information in F?<, hence its name, read0only" -ecause F?< is not volatile, the data stored there do not disappear when the computer is switched off" .tart0up instructions and other critical instructions are burned into F?< chips at the factory" 5hen we refer to main memory in this text, we mean F,< because that is the part of main memory that is normally accessible to the programmer" Secondary Storage Devices Computer systems provide storage in addition to main memory for two reasons" 8irst, computers need storage that is permanent or semipermanent so that information can be retained during a power loss or when the computer is turned off" .econd, systems typically store more information than will fit in memory" 8igure 1"4 shows some of the most frequently encountered secondary storage devices and storage media" <ost personal computers use two types of disk drives as their secondary storage devicesGhard drives and optical drives" Aard disks are attached to their disk drives and are coated with a magnetic material" 1ach data bit is a magneti:ed spot on the disk, and the spots are arranged in concentric circles called tracks" The disk drive readBwrite head accesses data by moving across the spinning disk to the correct track and then sensing the spots as they move by" The hard disks in personal computers usually hold several hundred gigabytes 7;-9 of data, but clusters of hard drives that store data for an entire network may provide as much as several terabytes 7T-9 of storage 7see Table 1"19" <ost of today s personal computers are equipped with optical drives for stor0 ing and retrieving data on compact disks 7C*s9 or digital versatile disks 7*D*s9 that can be removed from the drive" , C* is a silvery plastic platter on which a laser records data as a sequence of tiny pits in a spiral track on one side of the disk" ?ne C* can hold 4E) <- of data" , *D* uses smaller pits packed in a tighter spiral, allowing storage of 3"H ;- of data on one layer" .ome *D*s can hold four layers of dataGtwo on each sideGfor a total capacity of 1H ;-, sufficient storage for as much as nine hours of studio0quality video and multi0channel audio"

(I)URE "#1 .econdary .torage <edia


C* 8lash drive Aard disk

1"= Computer Aardware

TAB2E "#"
Term -yte Jilobyte <egabyte ;igabyte Terabyte

Terms /sed to Iuantify .torage Capacities


,bbreviation J<;T1quivalent to E bits 1,)=3 7=1 )9 bytes 1,)3E,6H4 7== )9 bytes 1,)H(,H31,E=3 7=( )9 bytes 1,)'',611,4=H,HH4 7=3 )9 bytes K 1)( K 1)4 K 1)' K 1)1 = Comparison to #ower of 1)

8lash drives such as the one pictured in 8ig" 1"4 use flash memory packaged in small plastic cases about three inches long that can be plugged into any of a computer s /.- 7/niversal .erial -us9 ports" /nlike hard drives and optical drives that must spin their disks for access to data, flash drives have no moving parts and all data transfer is by electronic signal only" &n flash memory, bits are represented as electrons trapped in microscopic chambers of silicon dioxide" Typical /.- flash drives store 1 to several ;- of data, but 430;- drives are also available" &nformation stored on a disk is organi:ed into separate collections called files" ?ne file may contain a C program" ,nother file may contain the data to be proc0 essed by that program 7a data file9" , third file could contain the results generated by a program 7an output file9" The names of all files stored on a disk are listed in the disk s directory " This directory may be broken into one or more levels of sub0 directories or folders, where each subdirectory stores the names of files that relate to the same general topic" 8or example, you might have separate subdirectories of files that contain homework assignments and programs for each course you are taking this semester" The details of how files are named and grouped in directories vary with each computer system" 8ollow the naming conventions that apply to your system"

Centra$ Pro!essing Unit


The central processing unit 7C#/9 has two roles: coordinating all computer operations and performing arithmetic and logical operations on data" The C#/ follows the instructions contained in a computer program to determine which operations should be carried out and in what order" &t then transmits coordinating control signals to the other computer components" 8or example, if the instruction requires scanning a data item, the C#/ sends the necessary control signals to the input device" To process a program stored in main memory, the C#/ retrieves each instruc0 tion in sequence 7called fetching an instruction9, interprets the instruction to determine what should be done, and then retrieves any data needed to carry out

Chapter 1 ?verview of Computers and #rogramming

that instruction" 2ext, the C#/ performs the actual manipulation, or processing, of the data it retrieved" The C#/ stores the results in main memory" The C#/ can perform such arithmetic operations as addition, subtraction, mul0 tiplication, and division" The C#/ can also compare the contents of two memory cells 7for example, 5hich contains the larger valueL ,re the values equalL9 and make decisions based on the results of that comparison" .ome computers have multiple C#/s 7 multiprocessors 9 or a multi0core C#/" These computers are capable of faster speeds because they can process different sets of instructions at the same time"

Input3Output 4evi!es
5e use inputBoutput 7&B?9 devices to communicate with the computer" .pecifically, they allow us to enter data for a computation and to observe the results of that computation" $ou will be using a keyboard as an input device and a monitor 7display screen9 as an output device" 5hen you press a letter or digit key on a keyboard, that character is sent to main memory and is also displayed on the monitor at the position of the cursor , a moving place marker 7often a blinking line or rectangle9" , computer keyboard has keys for letters, numbers, and punctuation marks plus some extra keys for performing special functions" The twelve function keys along the top row of the keyboard are labeled 81 through 81=" The activity performed when you press a function key depends on the pro0 gram currently being executed! that is, pressing 81 in one program will usually not pro0 duce the same results as pressing 81 in another program" ?ther special keys enable you to delete characters, move the cursor, and MenterN a line of data you typed at the keyboard" ,nother common input device is a mouse. , mouse is a handheld device used to select an operation" <oving the mouse around on your desktop moves the mouse cursor 7normally a small rectangle or an arrow9 displayed on the monitor s screen" $ou select an operation by moving the mouse cursor to a word or icon 7picture9 that represents the computer operation you wish to perform and then pressing a mouse button to activate the operation selected" A monitor provides a temporary display of the information that appears on its screen" &f you want hard copy 7a printed version9 of some information, you must send that information to an output device called a printer "

Computer etwor5s
The explosion we are experiencing in worldwide information access is primarily due to the fact that computers are now linked together in networks so they can com0 municate with one another" &n a local area network 7>,29, computers and other

1"= Computer Aardware

(I)URE "#6 >ocal ,rea 2etwork

4S2 !onne!tion &digita$ su+s!ri+er $ine' a high0speed &nternet connection that uses a telephone line and does not interfere with simultaneous voice communication on the same line

devices in a building are connected by cables or a wireless network, allowing them to share information and resources such as printers, scanners, and secondary stor0 age devices 7 8ig" 1"H 9" , computer that controls access to a secondary storage device such as a large hard disk is called a file server " >ocal area networks can be connected to other >,2s using the same tech0 nology as telephone networks" Communications over intermediate distances use phone lines, fiber0optics cables or wireless technology, and long0range com0 munications use either phone lines or microwave signals that may be relayed by satellite 78ig" 1"E9" , network that links many individual computers and local area networks over a large geographic area is called a wide area network 75,29 " The most well0known 5,2 is the &nternet, a network of university, corporate, government, and public0 access networks" The &nternet is a descendant of the computer network designed by the /"." *efense *epartment s 1'4' ,F#,net pro%ect" The goal of the pro%ect was to create a computer network that could continue to operate even if partially destroyed" The most widely used aspect of the &nternet is the 5orld 5ide 5eb 75559, the universe of &nternet0accessible resources that are navigable through the use of a graphical user interface 7;/&9 " &f you have a computer with a modem, you can connect to the information superhighway through a telephone line, television or fiber0optic cable, or through wireless or satellite communications" , modem 7modulatorBdemodulator9 converts binary computer data into audio tones that can be transmitted to another computer over a normal telephone circuit" ,t the computer on the receiving end, another modem converts the audio tones back to binary data" 1arly modems for telephone lines transmitted at only ()) baud 7()) bits per second9" Today s modems transmit over 6),))) bits per second, or if you have a digital subscriber line 7 *.> connection 9 or fiber0optics telephone line, the associated

Chapter 1 ?verview of Computers and #rogramming

(I)URE "#7 , 5ide ,rea 2etwork with .atellite Felays of <icrowave .ignals
.atellite

<icrowave tower

>ocal area network 7>,29

modem can transmit 1"6 million bits per second 7*.>9 or a few billion bits per sec0 ond 7fiber optics9 while allowing you to use the same line simultaneously for voice calls" C able &nternet access brings &nternet data to your computer at speeds of several billion bits per second using the same coaxial cable that carries cable TD" 5ireless and satellite communications provide data speeds comparable to cable"

1"( Computer .oftware

"#.

Computer Software
&n the previous section, we surveyed the components of a computer system, compo0 nents referred to collectively as hardware" 5e also studied the fundamental opera0 tions that allow a computer to accomplish tasks: repeated fetching and execution of instructions" &n this section we focus on these all0important lists of instructions called computer programs or computer software" 5e will consider first the software that makes the hardware friendly to the user" 5e will then look at the various levels of computer languages in which software is written and at the process of creating and running a new program"

Operating S-stem
the computer hardware is called the operating system 7?.9 " The operating sys0 tem of a computer is often compared to the conductor of an orchestra, for it is the software that is responsible for directing all computer operations and managing all computer resources" /sually part of the operating system is stored permanently in a read0only memory 7F?<9 chip so that it is available as soon as the computer is turned on" , computer can look at the values in read0only memory, but can0 not write new values to the chip" The F?<0 based portion of the ?. contains the instructions necessary for loading into memory the rest of the operating system code, which typically resides on a disk" >oading the operating system into memory is called booting the The collection of computer programs that control the interaction of the user and computer " Aere is a list of some of the operating system s many responsibilities: 1" =" (" 3" 6" 4" Communicating with the computer user: receiving commands and carrying them out or re%ecting them with an error message" <anaging allocation of memory, of processor time, and of other resources for various tasks" Collecting input from the keyboard, mouse, and other input devices, and pro0 viding this data to the currently running program" Conveying program output to the screen, printer, or other output device" ,ccessing data from secondary storage" 5riting data to secondary storage"

&n addition to these responsibilities, the operating system of a computer with multiple users must verify each individual s right to use the computer and must ensure that each user can access only data for which he or she has proper authori:ation" Table 1"= lists some widely used operating systems" ,n ?. that uses a com0 mand0line interface displays a brief message, called a prompt, that indicates its readiness to receive input, and the user then types a command at the keyboard" 8igure 1"' shows an entry of a /2&O command 7 ls temp/misc 9 requesting a list of the names of all the files 7 Gridvar.c, Gridvar.exe, Gridok.txt9 in subdirectory

Chapter 1 ?verview of Computers and #rogramming

TAB2E "#* 5idely /sed ?perating .ystem 8amilies Categori:ed by /ser &nterface Type
Command-Line Interface /2&O <.0*?. D<. Gra !ical "ser Interface <acintosh ?. 5indows ?.B= 5arp /2&O P O 5indow .ystem

misc of directory temp " &n this case, the prompt is mycomputer !" 7&n this figure, and

in all subsequent figures showing program runs, input typed by the user is shown in color to distinguish it from computer0generated text"9 &n contrast, operating systems with a graphical user interface provide the user with a system of icons and menus" To issue commands, the user moves the mouse or touch pad cursor to point to the appropriate icon or menu selection and pushes a button once or twice" 8igure 1"1) shows the window that pops up in <icrosoft 5indows H when you left0click on the .tart icon and then left0click on Computer" $ou can view the directories of the hard drive 7C:9, backup drive 78:9, optical drive 7*:9, or flash drive 71:9 by double0clicking the appropriate icon"

App$i!ation Software
,pplication programs are a database management application such as developed to assist a d-,.1 assists in data storage and quick keyword0based access to large collections of computer user in records" accomplishing Computer users typically purchase application software on C*s or by specific tasks" 8or down0loading files from the &nternet and install the software by copying the example, a word0 programs to the hard disk" 5hen buying software, you must always check that the processing program you are purchasing is compatible with both the operating system and the application such as computer hardware you plan to use" 5e have already discussed some of the differences <icrosoft 5ord among operating systems! now we will investigate the different languages or ?pen?ffice"org understood different processors" 5riter helps to create a document, a spreadsheet application such as <icrosoft ?ffice 1xcel helps to automate tedious numerical calculations and to generate charts that depict data, and

is not standardi:ed: There is a different machine language for every type of C#/" This same drawback also applies

1.3 Computer Software

<icrosoft ?ffice ,ccess or" "

Computer 2anguages
*eveloping new software requires writing lists of instructions for a computer to execute" Aowever, software developers rarely write in the language directly under0 stood by a computer, since this machine language is a collection of binary num0 bers" ,nother drawback of machine language is that it

Chapter 1 ?verview of Computers and #rogramming

TAB2E "#. , <achine >anguage #rogram 8ragment and &ts ,ssembly >anguage 1quivalent
<emory ,ddresses )))))))) )))))))1 ))))))1) ))))))11 )))))1)) )))))1)1 )))))11) <achine >anguage &nstructions )))))))) )))1)1)1 )))1)11) ))11)1)1 )111)111 L L ,ssembly >anguage &nstructions C>, ,** , ,** .T, , A>T ,L -L

to the somewhat more readable assembly language, a language in which computer operations are represented by mnemonic codes rather than binary numbers and variables can be given names rather than binary memory addresses" Table 1"( shows a tiny machine language program fragment that adds two numbers and the equivalent fragment in assembly language" 2otice that each assembly language instruction corresponds to exactly one machine instruction: The assembly language memory cells labeled , and - are space for variables! they are not instructions" The symbol L indicates that we do not know the contents of the memory cells with addresses )))))1)1 and )))))11)" To write programs that are independent of the C#/ on which they will be executed, software designers use high0level languages that combine algebraic expressions and symbols taken from 1nglish" 8or example, the machineBassembly language program fragment shown in Table 1"( would be a single statement in a high0level language:
a # a $ %&

This statement means Madd the values of variables a and %, and store the result in variable a 7replacing a s previous value9"N There are many high0level languages available" Table 1"3 lists some of the most widely used ones along with the origin of their names and the application areas that first populari:ed them" ,lthough programmers find it far easier to express problem solutions in high0level languages, there remains the problem that computers do 2?T understand these languages" Thus, before a high0level language program can be executed, it must first be translated into the target com0 puter s machine language" The program that does this translation is called a com0 piler " 8igure 1"11 illustrates the role of the compiler in the process of developing

1"( Computer .oftware

TAB2E "#/
>anguage 8?FTF,2 C?-?> >&.# C #rolog ,da .malltalk CPP +ava

Aigh0>evel >anguages
,pplication ,rea .cientific programming -usiness data processing ,rtificial &ntelligence .ystems programming ,rtificial &ntelligence Feal0time distributed systems ;raphical user interfaces! ob%ect0oriented programming .upports ob%ects and ob%ect0oriented programming .upports 5eb programming and programming ,ndroid applications ?rigin of 2ame (or mula tran slation Co mmon B usiness0 Oriented 2 anguage 2ist processing #redecessor language was named 2ogic pro gramming Ada ,ugusta -yron collaborated with nineteenth0century computer pioneer Charles -abbage ?b%ects MtalkN to one another via messages &ncremental modification of C 7PP is the C increment operator9 ?riginally named M?akN

and testing a high0level language program" -oth the input to and the output from the compiler 7when it is successful9 are programs" The input to the compiler is a source file containing the text of a high0level language program" The software developer creates this file by using a word processor or editor" The format of the source file is text, which means that it is a collection of character codes" 8or exam0 ple, you might type a program into a file called mypro'.c. The compiler will scan this source file, checking the program to see if it follows the high0level language s syntax 7grammar9 rules" &f the program is syntactically correct, the compiler saves in an ob%ect file the machine language instructions that carry out the program s purpose" 8or program mypro'.c, the ob%ect file created might be named mypro'. o%( " 2otice that this file s format is binary" This means that you should not send it to a printer, display it on your monitor, or try to work with it in a word proces0 sor because it will appear to be meaningless garbage to a word processor, printer, or monitor" &f the source program contains syntax errors, the compiler lists these errors but does not create an ob%ect file" The developer must return to the word processor, correct the errors, and recompile the program" ,lthough an ob%ect file contains machine instructions, not all of the instruc0 tions are complete" Aigh0level languages provide the software developer with many named chunks of code for operations that the developer will likely need" ,lmost all high0level language programs use at least one of these chunks of code called func0 tions that reside in other ob%ect files available to the system" The linker program combines these prefabricated functions with the ob%ect file, creating a complete

Chapter 1 ?verview of Computers and #rogramming

(I)URE "#"" 1ntering, Translating, and Funning a Aigh0>evel >anguage #rogram 7 #rocess of 1xecuting a C program 9
8ord Pro!essor 7editor9 /sed to type in program and corrections

Sour!e (i$e (ormat9 text

Compi$er ,ttempts to translate program into machine code /nsuccessful 1rror <essages

.uccessful

O+:e!t (i$e (ormat9 binary

Ot%er O+:e!t (i$es (ormat9 binary

2in5er Fesolves cross0references among ob%ect files

E;e!uta+$e (i$e 7load module9 (ormat9 binary

2oader Copies executable file into memory! initiates execution of instructions

&nput data

Fesults

1"( Computer .oftware

machine language program that is ready to run" 8or your sample program, the linker might name the executable file it creates mypro'.exe " ,s long as mypro'.exe is %ust stored on your disk, it does nothing" To run it, the loader must copy all its instructions into memory and direct the C#/ to begin execution with the first instruction" ,s the program executes, it takes input data from one or more sources and sends results to output andBor secondary storage devices" .ome computer systems require the user to ask the ?. to carry out separately each step illustrated in 8ig" 1"11 " Aowever, most high0level language compilers are sold as part of an integrated development environment 7&*19, a package that combines a simple word processor with a compiler, linker, and loader" .uch environ0 ments give the developer menus from which to select the next step, and if the devel0 oper tries a step that is out of sequence, the environment simply fills in the missing steps automatically"

E;e!uting a Program
To execute a machine language program, the C#/ must examine each program instruction in memory and send out the command signals required to carry out the instruction" ,lthough the instructions normally are executed in sequence, as we will discuss later, it is possible to have the C#/ skip over some instructions or execute some instructions more than once" *uring execution, data can be entered into memory and manipulated in some specified way" .pecial program instructions are used for entering or scanning a program s data 7called input data9 into memory" ,fter the input data have been processed, instructions for displaying or printing values in memory can be executed to display the program results" The lines displayed by a program are called the program output " >et s use the situation described in 8ig" 1"1= Gexecuting a water bill program stored in memoryGas an example" The first step of the program scans into memory data that describe the amount of water used" &n step =, the program manipulates the data and stores the results of the computations in memory" &n the final step, the computational results are displayed as a water bill"

.*

Chapter 1 ?verview of Computers and #rogramming

(I)URE "#"* 8low of &nformation *uring #rogram 1xecution


<emory <achine language program for computing water bill .tep 1 &nput data: meter readings #rogram input *ata entered during execution .tep = Central processing unit

Computed results

#rogram output .tep (

1"3 The .oftware *evelopment <ethod

"#/

T%e Software 4eve$opment ,et%od


#rogramming is a problem0solving activity" &f you are a good problem solver, you have the potential to become a good programmer" Therefore, one goal of this book is to help you improve your problem0solving ability" #roblem0solving methods are covered in many sub%ect areas" -usiness students learn to solve problems with a systems approach while engineering and science students use the engineering and scientific method" #rogrammers use the software development method"

Software 4eve$opment ,et%od


1" =" (" 3" 6" 4" .pecify the problem requirements" ,naly:e the problem" *esign the algorithm to solve the problem" &mplement the algorithm" Test and verify the completed program" <aintain and update the program"

#F?->1< .pecifying the problem requirements forces you to state the problem clearly and unambiguously and to gain a clear understanding of what is required for its solution" $our ob%ective is to eliminate unimportant aspects and :ero in on the root problem" This goal may not be as easy to achieve as it sounds" ,2,>$.&. ,naly:ing the problem involves identifying the problem 7a9 inputs, that is, the data you have to work with! 7b9 outputs, that is, the desired results! and 7c9 any additional requirements or constraints on the solution" Compute and display the total cost of apples given the number of pounds of apples purchased and the cost per pound of apples " 2ext, summari:e the information contained in the underlined phrases:

Chapter 1 ?verview of Computers and #rogramming

#roblem &nputs
)ua*tity o+ apples purc,ased -i* pou*ds. cost per pou*d o+ apples -i* dollars per pou*d.

#roblem ?utput
total cost o+ apples -i* dollars.

?nce you know the problem inputs and outputs, develop a list of formulas that specify relationships between them" The general formula Total cost Q /nit cost R 2umber of units computes the total cost of any item purchased" .ubstituting the variables for our particular problem yields the formula Total cost of apples Q Cost per pound R #ounds of apples &n some situations, you may need to make certain assumptions or simplifications to derive these relationships" This process of modeling a problem by extracting the essential variables and their relationships is called abstraction " *1.&;2 *esigning the algorithm to solve the problem requires you to develop a list of steps called an algorithm to solve the problem and to then verify that the algorithm solves the problem as intended" 5riting the algorithm is often the most difficult part of the problem0solving process" *on t attempt to solve every detail of the problem at the beginning! instead, discipline yourself to use top0down design" &n top0down design 7also called divide and conquer 9, you first list the ma%or steps, or subproblems, that need to be solved" Then you solve the original problem by solving each of its subproblems" <ost computer algorithms consist of at least the following subproblems"
,>;?F&TA< 8?F , #F?;F,<<&2; #F?->1<

1" ;et the data" =" #erform the computations" (" *isplay the results" ?nce you know the subproblems, you can attack each one individually" 8or example, the perform0the0computations step may need to be broken down into a more detailed list of steps through a process called stepwise refinement "

1"3 The .oftware *evelopment <ethod

&<#>1<12T,T&?2 &mplementing the algorithm 7step 3 in the software development method9 involves writing it as a program" $ou must convert each algorithm step into one or more statements in a programming language" T1.T&2; Testing and verifying the program requires testing the completed program to verify that it works as desired" *on t rely on %ust one test case" Fun the program several times using different sets of data to make sure that it works correctly for every situation provided for in the algorithm" <,&2T12,2C1 <aintaining and updating the program involves modifying a program to remove previously undetected errors and to keep it up0to0date as government regulations or company policies change" <any organi:ations maintain a program for five years or more, often after the programmers who originally coded it have left or moved on to other positions" , disciplined approach is essential if you want to create programs that are easy to read, understand, and maintain" $ou must follow accepted program style guidelines 7which will be stressed in this book9 and avoid tricks and programming shortcuts"

"#0

App$-ing t%e Software 4eve$opment ,et%od


Throughout this book, we use the first five steps of the software development method to solve programming problems" These example problems, presented as Case .tudies, begin with a problem statement" ,s part of the problem analysis, we identify the data requirements for the problem, indicating the problem inputs and the desired outputs" 2ext, we design and refine the initial algorithm" 8inally, we implement the algorithm as a C program" 5e also provide a sample run of the program and discuss how to test the program" 5e walk you through a sample case study next" This example includes a running commentary on the process, which you can use as a model in solving other problems"

CASE STU4<
#F?->1<

Converting ,i$es to =i$ometers

$our summer surveying %ob requires you to study some maps that give distances in kilometers and some that use miles" $ou and your coworkers prefer to deal in metric measurements" 5rite a program that performs the necessary conversion" ,2,>$.&. The first step in solving this problem is to determine what you are asked to do" $ou must convert from one system of measurement to another, but are you supposed to convert from kilometers to miles, or vice versaL The problem states that you prefer to deal in metric measurements, so you must convert distance measurements in miles to kilometers" Therefore, the problem input is distance in miles and the problem output is distance in kilometers " To write the program, you need to know the rela0 tionship between miles and kilometers" Consulting a metric table shows that one mile equals 1"4)' kilometers" The data requirements and relevant formulas are listed below" miles identifies the memory cell that will contain the problem input and kms identifies the memory cell that will contain the program result, or the problem output"

*,T, F1I/&F1<12T.

#roblem &nput
miles // t,e dista*ce i* miles//

#roblem ?utput
kms // t,e dista*ce i* kilometers //

Felevant 8ormula 1 mile Q 1"4)' kilometers *1.&;2 2ext, formulate the algorithm that solves the problem" -egin by listing the three ma%or steps, or subproblems, of the algorithm"
,>;?F&TA<

1" ;et the distance in miles" =" Convert the distance to kilometers" (" *isplay the distance in kilometers" 2ow decide whether any steps of the algorithm need further refinement or whether they are perfectly clear as stated" .tep 1 7getting the data9 and step ( 7displaying a value9 are basic steps and require no further refinement" .tep = is fairly straightforward, but some detail might help: .tep = Fefinement ="1 The distance in kilometers is 1"4)' times the distance in miles" 5e list the complete algorithm with refinements below to show you how it all fits together" The algorithm resembles an outline for a term paper" The refinement of step = is numbered as step ="1 and is indented under step ="
,>;?F&TA< 5&TA F18&21<12T.

1" ;et the distance in miles" =" Convert the distance to kilometers" ="1 The distance in kilometers is 1"4)' times the distance in miles" (" *isplay the distance in kilometers" >et s desk check the algorithm before going further" &f step 1 gets a distance of 1)") miles, step ="1 would convert it to 1"4)' 1)")) or 14")' kilometers" This correct result would be displayed by step ("

(I)URE "#". <iles0to0Jilometers Conversion #rogram


0. 2. 3. 4. 5. // / 1o*verts dista*ce // 2i*clude 3stdio.," 2de+i*e 456789:75;<9 i* miles to // // kilometers. pri*t+@ sca*+ de+i*itio*s // co*versio* co*sta*t //

0.60=

6. 7. i*t >. mai*-void. =. ? 00. dou%le miles@ // i*put - dista*ce i* miles. // 00. kms& // output - dista*ce i* kilometers // 02. 03. // Get t,e dista*ce i* miles. // 04. pri*t+-A9*ter t,e dista*ce i* miles" B.& 05. sca*+-ACl+B@ Dmiles.& 06. 07. // 1o*vert t,e dista*ce to kilometers. // 0>. kms # 456789:75;<9 / miles& 0=. 20. // Eisplay t,e dista*ce i* kilometers. // 20. pri*t+-AF,at e)uals C+ kilometers.G*B@ kms.& 22. 23. retur* -0.& 24. H .ample Fun 9*ter t,e dista*ce i* miles" 00.00 F,at e)uals 06.0=0000 kilometers.

&<#>1<12T,T&?2 To implement the solution, you must write the algorithm as a C program" To do this, you must first tell the C compiler about the problem data requirementsGthat is, what memory cell names you are using and what kind of data will be stored in each memory cell" 2ext, convert each algorithm step into one or more C statements" &f an algorithm step has been refined, you must convert the refinements, not the original step, into C statements" 8igure 1"1( shows the C program along with a sample execution or run" 8or easy identification, the program statements corresponding to algorithm steps are in

color as is the input data typed in by the program user" *on t worry about under0 standing the details of this program yet" 5e explain the program in the next chapter" T1.T&2; Aow do you know the sample run is correctL $ou should always examine program results carefully to make sure that they make sense" &n this run, a distance of 1)") miles is converted to 14")' kilometers, as it should be" To verify that the program works properly, enter a few more test values of miles" $ou don t need to try more than a few test cases to verify that a simple program like this is correct"

You might also like