Vous êtes sur la page 1sur 46
Overview of Computers and Programming 4.1 ELECTRONIC COMPUTERS THEN AND NOW 1.2 COMPUTER HARDWARE 1.3. COMPUTER SOFTWARE 1.4 ALGORITHM 1.5 SEQUENCE, SELECTION, AND ITERATION 4 1.6 FLOWCHARTS ‘THE SOFTWARE DEVELOPMENT METHOD fe é 1.8 APPLYING THE SOFTWARE DEVELOPMENT METHOD CASE STUDY: CONVERTING MILES TO KILOMETERS CHAPTER REVIEW *% computer 2 machine that can rece, store, ‘transfor, and output data of a kind I, developed countries, life inthe twenty-first century is conducted in a ver- itable sea of computers. From the eoffeepot that tums itself on to brew your moming eoffee to the microwave that cooks your breakfast to the automobile that you drive to work to the automated teller machine you stop by for cash, vir- tually every aspect of your life depends on computers. These machines which receive, store, proer ss, and output information can deal with data ofall kinds: rmnbers, text, images. graphics, and sound, to name a few. ‘The computer program’ role in this technology is essential; without alist of instructions to follow, the computer is virtually useless. Programming languages allow us to write those programs and thus to communicate with computers. ‘You are about to begin the study of computer science using one of the most versatile programming languages available today: the G language. This chapter introduces you to the computer and its components and to the major categories of programming languages. It discusses how C programs are processed by @ compater. It also deseribes a systematic approach to solving programming prob- lems called the software development method and shows you how to apply i 1.1 Electronic Computers Then and Now computer chip (microprocessor chip) assican chip Containing the circuitry fora computer processor Tn ovr everyday life, we come in contact with computers frequently, some of us using computers for word processing or even having studied programming in high school, But it wasn't always this way. Not so long. agp, most people considered computers to be mysterious devices whose seerets were known only by afew eom- puter wizards ‘The first electronic computer was built in the late 1980s by Dr. John Atanasoff and Clifford Berry at Lowa State University, Atanasoff designed his computer to assist graduate students in muclear physics with their mathematical computations. ‘The first large-scale, general-purpose clectronie digital computer, called the ENIAC, was completed in 1946 atthe University of Pennsylvania with fund- ing from the U.S. Army. Weighing 30 tons and occupying a 30-by-50-foot space. the ENIAG was used to compute ballisties tables, predict the weather, and ‘make atomie energy caleulations, ‘These early computers used vacuum tubes as their basic electronic compo- nent. Technological advances in the design and manufacture of electronic com- ponents led to new generations of computers that were considerably smaller, faster, and less expensive than previous ones. Using today’s technology, the entire ercuitry of a computer processor can be packaged in a single electronic component called a computer or micro- processor chip (Fig. 1.1), which is about the size of a postage stamp. Their affordability and small size enable computer chips to be installed in watches, FIGURE 1.1 ‘The Inte! Pentium 4 Processor chipis an integrated circuit containing the full carcuitry of a central processing unit. This processor can execute a simple instruction such as an integer addition inone sixbillonth of a second Gepinted by permission of ite Comparten, © inte Corporation 2003) herdware the acc computer equipment software the tof programs assacated ‘tha computer program ato! Fnactons that fables acomputer to perlorn spect ask binary number 2 numberwbose dts te oand Li Hledionic Computer Then and Now pocket calculators, cameras, hone appliances, automobiles, and, of course, computers Today; « common sight in offices and homes is a personal computer, which cean cost less than $1000 and sit on a desk and yet has as much computational power as one that 20 years ag> cost more than $100,000 and filled a 8-by-12-foot oom. Even smaller computers ean fit inside a briefcase (Fig. 1.2a) or your hand (Fig. 12h), Modem computers are categorized according to their size and perform ance. Personal computers, shown in Fig. 1.2. are used by a single person at a time. Large real-time transaction processing systems, such as ATMs and other banking networks, and corporate reservations systems for motel, airlines, and rental cars use: mainframes, very powerful and reliable computers. The largest capacity and fastest mainframes are called supercomputers and are used by research laboratories and in computationally intensive applications such as weather forecasting The elements of a computer system fall into two major categories: hardware and software, Hardware is the equipment used to perform the necessary com= piatations and includes the central processing unit (CPU), monitor, keyboard, ‘mouse, printer, and speakers. Software consists of the programs that enable us to solve problems with a computer by providing it with lists of instructions to perform Fr" pragraninlaya computer has wallenpone sigiftnat changesavor tha years. Initially, the task was very diffieult, requiring programmers to write their program instructions as long binary numbers (sequences of Os and 15), High level programming languages such as C make programming much easier [ERR ort + overview of Computers and Programming FIGURE 1.2 (3) Notebook Computer (ThinkPad®, Courtesy of SM) 4b) Palmtop Computer (Sony ‘Clie PDA ®, Courtesy of Sony). (©) Desktop Computer UBM Net¥sta Desktop, Courtesy Of IM ® ) 126 computer Hardware MBB EXERCISES FOR SECTION 1.1 Self-Check 1. Is computer program a piece of hardware or i it software? 2. Forwhat applications are mainframes used? 1.2 Computer Hardware Despite significant variations in cost, size, and capabilities, modem computers resemble one another in many’ basie ways. Essentially, most consist of the fol- lowing components Main memary {Secondary memory. which includes starage devices such shar disks, floppy disks, disks, CDs, and DVDs. Cental proses wat Tp devices suchas keyboards, mouses, touch pads, scanners S Gltpurdeices such ab mentors, printers and speakers Figure 1.3 shows how these components interact in « 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 ean be executed. Normally the person using a program (the program user) must supply some data torbe processed. These data are entered through an input deve and are stored in the computer's main memory. where they can be accessed and manipulated by the central processing wnit, The results ofthis manipulation are then stored back in main memory. Finally, the information in main memory can be displayed through an output decice. In the remainder of this section, we describe these ‘components in more deta. memory cell 2n ‘Rawaual storage ‘bation !a memory address of a memory all ie relate Dosti of memory Eslinthe computers ‘mam memory contents of a memory call the Information stored na ‘memory el ether 3 program suchen or aa Memory Memory isan essential component in any computer. Lets look at what it eonstats ‘of and how the computer works with it Anatomy of Memory Imagine the memory of a computer as an ordered sequence of storage locations called memory cells (Fig, 1.4). 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. Figure 1.4 shows a computer ‘memory consisting of 1000 memory cells with addresses 0 throngh 999. Most computers, however, have millions of individual memory cells, each with its own addres. ‘The data stored in a memory cell are called the contents of the cell. Every ‘memory cell always has some contents, although we may have no idea what HBB nr vere of computes and Programming FIGURE 1.3 Components of a ‘Computer ‘Secondary storage FIGURE 1.4 1000 Memory Cells in Main Memory stored program oncept a computer's obilty to store program instructions in mein memory for execution Memory Address Contents ° ~27 8] 1 334 2 2.0051 3 26 4 a 998 x 99 78.42] they are. In Fig. 1.4, the contents of memory cell 3 are the number ~96 and the contents of memory cell 4 are the letter I. Although not shown in Fig. 1.4, a memory cell can also contain a program instruction. The ability to store programs as well as data is called the stored rogram concept: A program’ instructions must be stored m main memory before they can be executed. We ean change the computer’ operation by storing different program in memory. FIGURE 1.5 Relationship Between a Byte and a Bit byte the omount of storage requied to Stores single character bit a binary digit: a0 orat data storage setting the individual bits of a memory cell to 0 ort, destroying is previous contents data retrieval copying the contents of a pantcular memory cal to another storage 12+ computer Hardnare Bit Jootot10 fi “Byte Bytes and Bits A memory cell is actually a grouping of smaller units called bytes. A byte is the amount of storage required to store a single character, such asthe letter H in memory cell 4 of Fig. 1.4. The number of bytes a memory cell can contain varies from computer to computer. A byte is composed of even smaller units of storage called bits (Fig. 1.5). The term bit, deriving from the words binary digit, i the smallest element a computer can deal with. Binary refers toa number systom based on two numbers, 0 and 1, soa bit is either a0 or a 1. Generally there are eight bits toa byte. Storage and Retrieval of Information in Memory Each value in memory is represented by a particular pattern of Os and 1s. A 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 0 or 1, destroying the previous contents ofthe cell in the process. To retrieve a value from a memory cell, the computer copies the pattern of 0s 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 information—character, ‘ion—to be stored or retrieved. random access memory (RAM) cory that temporary stores programs, deta, ‘and results read-only memory (Rom) the part of main mem- ‘ory that permanently sores programs or ‘ents disappear when the computer is switched off Main Memory Main memory stores programs, data, and results. Most computers have two types of main memory: random access memory (RAM), which offers temporary storage of programs and data, and read-only memory (ROM), which stores programs or data permanently. RAM temporarily stores programs while they are being executed (carried out) by the computer. It also temporarily stores such data as numbers, names, and even pictures while a program is manipulating them, RAM is usually volatile memory, which means that everything in RAM will be lost when the computer is switched off. ROM, on the other hand, stores information permanently within the com= puter. The computer can retrieve (or read), but eannot store (or write), infor= ‘mation in ROM, hence its name, read-only. Because ROM is not volatile, the data stored there do not disappear when the computer is switched off, Start-up instructions and other critical instructions are burned into ROM chips atthe fac- tory. When we refer to main memory in this text, we mean RAM because that is the part of main memory that is normally aecessible to the programmer. Secondary Storage Devices Computer systems provide storage in addition to main memory for two reasons. First, computers need storage that is permanent or semipermanent so that information can be retained during a power loss or when the computer is tured off. Second, systems typically store ‘more information than will fit in memory. [RRB] vnie 1+ overview of computers and Programming FIGURE 1.6 Secondary Storage Media ‘secondary storage ‘nits such a5 disks or ‘apes that retain data ‘even when the power to the disk drive or tape drive off disk thin platter of ‘metal or pastic on hich data are represented by ‘magnetized spots frranged in tacks Figure 1.6 shows some of the most frequently encountered secondary storage devices and storage media. Most personal computers use two types of disk drives as their secondary storage devices: Hard disks are usually attached to their disk drives, whereas floppy disks and zip disks are removable. The disk itself is a thin platter of metal or plastic coated with a magnetic material. Each data bit is a magnetized spot on the disk, and the spots are arranged in concen- tric cirles called tracks. The disk drive read/write head accesses data by moving across the spinning disk to the correct track and then sensing the spots as they move by. A typical high-density floppy disk can store 1.44 MB (megabytes—see ‘Table 1.1) of data, a zip disk can store 100 MB or 250 MB, and some hard disks provide many gigabytes (GB) of storage. CD drive device that uses a laser to access for store data on a compact disk digital video disk (DVD) snery plastic platter with up to 17 GB of data storage file named collection of data stored on a disk directory 2 ist of thenames of files stored on a disk Most of today’s personal computers are equipped with CD drives for read- ing data stored on compact disks. Some of these drives can also write dita to CDs. A CD 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. One CD can hold 680 MB of data. An increasingly common secondary storage device that uses similar tech- nology is the Digital Video Disk (DVD) drive. By using smaller pits packed in a tighter spiral, a DVD stores 4.7 GB of data on one layer. Some DVDs can hold four layers of dats—two on each side—for a total capacity of 17 gigabytes, suf- ficient storage for as much as nine hours of studio-quality video and multi- channel audio. Information stored on a disk is organized into separate collections called files. One file may contain a C program. Another file may contain the data to be processed by that program (a data file). A third file could contain the results generated by a program (an output file). The names of all files stored on a disk are listed in the disk’s directory. This directory may be broken into one or TABLE 1.1. Terms Used to Quantify Storage Capacities ‘Comparison Term Abbreviation Equivalent to ‘to Power of 10 Bye a abis Kilobyte Ke 1,024 (2) bytes 210 Megabyte MB 1,048,576 (2 bytes > 108 Gigabyte GB 1,073,741,824(2%) bytes > 10 Terabe 8 1,099,511,627,776 @*) bytes > 1012 subdirectory alist lof the names of files, that relate 103 particular topic central processing unit (CPU) coordinates all computer operations and performs anthmetic an logical ‘operations on data fetching an Instruction ‘retrieving an instruction from ‘mein memory register high-speed memory location inside the CPU 1.2+ Computer Hardware HIB nore levels of subdirectories, where each subdirectory stores the names of files that relate to the same general topic. For example, you might have separate sub- directories 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. Follow the naming ‘conventions that apply to your system Central Processing Unit ‘The central processing unit (CPU) has two roles: coordinating all computer ‘operations and performing arithmetic and logical operations on data. The CPU follows the instructions contained in a computer program to determine which ‘operations should be carried out and in what order. It then transmits coordinating ‘control signals to the other computer components. For example, if the instruction requires scanning a data item, the CPU sends the necessary control signals to the input device. To process a program stored in main memory, the CPU retrieves each instruction in sequence (called fetching an instruction), interprets the instruction to determine what should be done, and then retrieves any data needed to carry out that instruction. Next, the CPU performs the actual manip- ulation, or processing, of the data it retrieved. The OPU stores the results in ‘main memory, ‘The CPU can perform such arithmetic operations as addition, subtraction, ‘multiplication, and division, The CPU can also compare the contents of two ‘memory cells (for example, Which contains the larger value? Are the values equal?) and make decisions based on the results of that comparison. The circuitry of a modern CPU is housed in a single integrated circuit or chip, millions of miniature circuits manufactured in a sliver of silicon. An inte~ arated circuit (IC) that isa full central processing unit i called a microprocessor. A CPUS current instruction and data values are stored temporarily inside the CBU in special high-speed memory locations called registers. cursor a moving place marker that ‘appears on the monitor function keys special keyboard keys used to select a particular ‘operation: operation selected depends on program baing used Input/Output Devices We use input/output (I/O) devices to communicate with the computer. Specifically, they allow us to enter data for a computation and to observe the results of that computation. You will be using a keyboard (Fig. 1.7) as an input device and a monitor (display screen) as an output device. When 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 eursor, a moving place marker (often a blinking line or rectangle). A computer keyboard resembles a typewriter keyboard except for some extra keys for performing special functions. For example, on the computer keyboard shown in Fig. 1.7, the 12 keys in the top row labeled F1 through F12 are funetion keys. The activity performed when you press a function key depends on the program currently being executed; that is, pressing F1 in one program will usually not produce the same results as pressing F1 in TB ri + overview of computers and programming FIGURE 1.7 Keyboard for IBM-Type Computers, Escape key “Tob Gaps tock ~ key shit key 5 Funetion Backepace —_Entor (Return) Num lock keys Shey rey yey FEEEEILE Se] E Numeric EEE TT aeelcoslewe keypad Control Anernate Deieio? Caraor conor key key key keys: mouse an input device that moves Its cursor on ‘the computer screen to select an operation Icon a picture repre- senting acomputer operation printer an output device that produces a hard copy of information senttort local area network (AN) computers, Printers, scanners, and orage devices Connected by cables for intercommurication file server the ‘computer na network ‘that controls access to a secondary storage Gevice suchas ahars sk another program. Other special keys enable you to delete characters, move the cursor, and “enter” a line of data you typed at the keyboard (see the high- lighted parts of Fig. 1.7) Another common input deviee is a mouse. A mouse is a handheld device ‘used to seleet an operation. When you move the mouse around on your desktop, rubber ball attached to the mouse rotates and simultaneously moves the mouse cursor (normally a small reetangle or an arrow) displayed on the monitor's screen. You select an operation by moving the mouse cursor to a word or feo (picture) 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. If you want hard copy (a printed version) of some information, you ‘must send that information to an output device called a printer, Computer Networks The explosion we are experiencing in worldwide information access is pri- marily due to the fact that computers are now linked together in networks so they can communicate with one another. In a local area network (LAN), computers and other devices in a building are connected by cables, allowing them to share information and resources such as printers, sean- ners, and secondary storage devices (Fig. 1.8). A computer that controls access to a secondary storage dovice such as a large hard disk is called a file server. Local area networks can be connected to other LANs using the same tech- nology as telephone networks. Communications over intermediate distances use phone lines, and long-range communications use either phone lines or microwave signals that may be relayed by satellite (Fig. 1.9). 1.26 Computer Hardware (AH FIGURE 1.8 Local Area Network FIGURE 1.9 A Wide Area Network with Satellite Relays of Microwave Signals on oe sate ‘Local tea netwark (LAN) wide area network (WAN) a netvrork such asthe internet that connects computers and LAN over a large geographic area ‘A network that links many individual computers and local area networks over « large geographic area is called a wide area network (WAN). The most well-known WAN is the Internet, a network of university, corporate, govern- ‘ment, and public-aecess networks. The Internet is a descendant of the com- puter network designed by the U.S. Defense Department's 1969 ARPAnet project. The goal of the project was to create a computer network that could continue to operate even if partially destroyed. The most widely used aspect of HERR uses + overiwof computers and Programming World Wide Web (WWW) apart of the Internet whose graphical User interfaces make ‘associated network the Intemet is the World Wide Web (WWW), the universe of Internet-acces- sible resources that are navigable through the use of a graphical user inter- face (GUD). If you have a computer with a modem, you can connect to the information resources easly navigable superhighway through a telephone line. A modem (modulator/demodulator) con- Frapheal user interface ests Linary computer data into audio tones that can be transtnitted to another spayed to alow user to” computer over a normal telephone circuit. At the compater on the reeciving end, select commands and 43t2. another modem converts the audio tones back to binary data. Early modems trans modem a device that Converts binary data into mitted at only 300 baud (300 bits per second). Today’s modems transmit over 50,000 seule Sorc thet can te. bits per second, or if you have a digital subscriber line (DSL connection), the transmitted between computers over telephone lines DSL connection (digital subscriber line) 2 Figh-speed Internet ‘connection that uses a telephone tne and does ot iretre wit ‘Smultaneous vice simultaneous voke Comaunicaton onthe ‘able Internet access ‘two-way high-speed transmission of internet (In this figure, and in all subsequent figures showing program runs, input typed by the user is shown in color to distinguish it from computer-generated text.) In 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, track ball, or touch pad cursor to point to the appropriate icon or menu selection and pushes a button once or twice. Figure 1.11 shows the window that pops up when you double-click on the “My Computer” icon in the top-left TABLE 1.2 Widely Used Operating Systems Categorized by User interface Type Command-Line interface Graphical User interface UNI Macintosh OS vs-Dos Windows us 0872 Warp UNIX + X Window System HB 62% 1 overview of computers and Programming FIGURE 1.10 Entering a UNIX Command for Directory Display mycomputer:-> 1c tomp/nise Gridvar.c Gridvar.exe Gridok.dat mycomputer:-> FIGURE 1.11 ‘Accessing Disk Drive through ‘Windows application Software used for @ spect task such as sword processing, ‘accounting, or data: base management install make an application avaiable on ‘2 computer by copying ‘from diskettes or CDs tothe computer's hard drive comer of the desktop of a Windows GUL. You can view the directories of the floppy disk (A:), hard drive (C:), CD, or zip disk by double-clicking the appro- priate icon, Application Software Application programs are developed to assist a computer user in accomplishing specific tasks. For example, a word-processing application such as Microsoft Word or WordPerfect helps to create a document, a spreadsheet application, such as Lotus 1-2-3 or Excel helps to automate tedious numerical calculations and to generate charts that depict data, and a database management application such as Access or dBASE assists in data storage and quick keyword-based access to large collections of records. ‘Computer users typically purchase application software on CDs and install the software by copying the programs from the CD to the hard disk. When buying software, you must always cheek that the program you are purchasing is compatible with both the operating system and the computer hardware you plan to use, We have already diseussed some of the differences among operating, systems; now we will investigate the different languages understood by different processors. machine language binary number codes Understood by a spe ce CP sssembly language mnemonic codes that Correspond to machine language instructions igh teva language mmachinesndependert programm onstage fot combines age. bra exoretons ond Ergish mba 13+ Computersotware Computer Languages Developing new software requires writing lists of instructions for a computer to execute. However, software developers rarely write in the language directly understood by @ computer, since this machine language is a collection of binary numbers. Another drawback of machine language is that it is not stan- dardized: There is a different machine language for every type of CPU. This same drawback also applies to the somewhat more readable assembly la ‘guage, 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.3 shows a tiny machine language progr fragment that adds two numbers and the equivalent fragment in assembly lan- guage. Notice that each assembly language instruction corresponds to exactly cone machine instruction: The assembly language memory cells labeled A and B are space for variables; they are not instructions. The symbol 7 indicates that we do not know the contents of the memory cells with addresses 00000101 and (00000110. ‘To write programs that are independent of the CPU on which they will be executed, software designers use high-level languages that combine algebraic expressions and symbols taken from English. For example, the machine/assem- bly language program fragment shown in Table 1.3 would be a single statement in a high-level language: This statement means “add the values of variables 2 and », and store the result in variable a (replacing 2's previous value).” There are many high-level languages available, Table 1.4 lists some of the ‘most widely used ones along with the origin of their names and the application areas that first popularized them, Although programmers find it far easier to ‘express problem solutions in high-level languages, there remains the problem that computers do NOT understand these languages. Thus, before a high-level language program can be executed, it must first be translated into the target TABLE 1.3 A Machine Language Program Fragment and Its Assembly Language Equivalent ‘Memory Addresses ‘Machine Language ‘Assembly Language Instructions Instructions ‘00000009 ‘00000009 ca ‘00000001 00010101 A0D A, ‘00000010 0010110 A0D8 00000011 00110101 STAA 00000100 orton Hur 00000101, ? Ar 00000110 > a? [ERR urs overview of computers and Programming TABLE 1.4 High-Level Languages Language ‘Application Are Origin of Name FORTRAN Scientific programming Formula translation oso. Business data processing Common Business-Oriented Language use ‘ctf intetigence List processing c Systems pregeaming Predecessor language was named 8 Prolog ‘Attica inteligence Logic programming Ada Real-time distributed systems ‘Ada Augusta Byron collaborated with nineteenth-century computer pioneer Charles Babbage Salta Graphical user interfaces Objects “talk” to one another via messages ‘object-oriented programming ce Supports objects and object-oriented Incremental maaification of C (4+ is programming the C increment operator) saa Supports Web programming Originally named "Oak" ‘compiler Sottware that tans- lates a high-level lan- quage program nto ‘machine language source file file Containing a program ‘writen ina high-level language; the input for acompler syntax grammar ‘les of a programming language object file file of machine language instructions that the ‘output of a compiler linker software that combines object fies and resolves cross- references to create an executable machine language program computer's machine language. The program that does this translation is called a compiler. Figure 1.12 illustrates the role of the compiler in the process of developing and testing a high-level language program. Both the input to and the ‘output from the compiler (when it is successful) are programs. The input to the compiler is a source file containing the text of a high-level language program. ‘The software developer creates this file by using a word processor or editor. The Format of the sourec file is text, which means that itis a collection of character codes. For example, you might type a program into a file called sypzog.c. The compiler will scan this source file, checking the program to see if it follows the high-level language’ syntax (grammar) rules. If the program is syntactically correct, the compiler saves in an object file the machine language instructions that carry out the program’s purpose, For program nypreg.c, the ebject file cre- ated might be named myprog.ob3. Notice 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 processor because it will appear to be meaningless garbage to a word processor, printer, or monitor. If the source program contains syntax errors, the compiler lists these errors but does not create an object file. ‘The developer must retum to the word processor, correct the errors, and recom pile the program, Although an object file contains machine instructions, not all of the instruc- tions are complete. High-level languages provide the software developer with ‘many named chunks of code for operations that the developer will likely need. Almost all high-level language programs use at least one of these chunks of code called functions that reside in other object files available to the system. The linker program combines these prefabricated functions with the object file, ere- ating a complete machine language program that is ready to run. For your sample program, the linker might name the exceutable file it creates nyproz.exe. 4s Computer vortware EN ing, and Running a High-Level Language Progearh As long as mypzog.exe is just stored on your disk, it does nothing, To rum it, the Joader must copy all its instructions into memory and direct the CPU to begin exe ction with the first instruction. As the program executes, it takes input data from ‘one or more sources and send results to output andV/or secondary storage devices. Some computer systems require the user to ask the OS to carry out sepa- rately each step illustrated in Fig. 1.12. However, many high-level language HEB 6 overview of computers and Programming integrated development ‘environment (IDE) software package ‘combining a word processor, compiler, linker, loader, and compilers are sold as part of an integrated development environment (IDE), a package that combines a simple word processor with a compiler, linker, and loader. Such environments give the developer menus from which to select the next step, and if the developer tries a step that is out of sequence, the environ- ment simply fills in the missing steps automaticaly. toals for finding ertors The user of an integrated development environment should be aware that the environment may not automatically save to disk the source, object, and exe- cutable files. Rather, it may simply leave these versions of the program in mem- ory. Such an approach saves the expenditure of time and disk space needed to make copies and keeps the code readily available in memory for application of the next step in the translation/execution process, However, the developer can risk losing the only copy of the source file in the event of a power outage or se ‘ous program error. To prevent such a loss when using an IDE, be sure to expli itly save the source file to disk after every modification before attempting to run the program, Executing a Program To execute a machine language program, the CPU must examine each program instruction in memory and send out the command signals required to carry out the instruction, Although the instructions normally are executed in sequence, as swe will discuss later, itis possible to have the CPU skip over some instructions or execute some instructions more than once. FIGURE 1.13 _ Flow of Information During Program Execution input data the data values thal are scanned bya program program output the lines displayed by 2 pregtar Memory During execution, data can be entered into memory and manipulated in some specified way. Special program instructions are used for entering or scan- ning a programs data (called input data) into memory. After the input data have heen 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. Let's use the situation described in Fig. 1.13—executing a water bill pro- gram stored in memory—as an example. The first step of the program scans into memory data that describe the amount of water used. Tn step 2, the pro- gram manipulates the data and stores the results of the computations in mem- ‘ny In the final step, the computational results are displayed as a water bill. MM) EXERCISES FOR SECTION 1.3 Self-Check 1. What do you think these five high-level language statements mean? stbscr x= y sa, G=e-bear +1; kelvin = celsius + 273.15; 2, List two reasons why it would be preferable to write a program in C rather than in machine language. 3. Would a syntax error be found in a source program or an object program? What system program would find a syntax error if one existed? What sys- tem program would you use to correct it? 4. Explain the differences among the source program, the object program, and an executable program. Which do you create, and which does the compiler ereate? Which does the linker or loader ereate? 1.4 Algorithm Algorithm isa very popular technique used to obtain solution fora given problem. An algorithm is defined as a finite set of steps that provide a chain of actions for solving a definite nature of problem.’ Each step in the algorithm should be well defined. This will enable the reader to translate each step into a program. The gradual procedure for solving.a problem is illustrated in this section ‘An algorithm is a well-organized, prearranged, and defined textual compu {ational module that receives some value or a set of values as input and provides single value or a set of values as output, These well-defined computational steps are arranged in a sequence that processes the given input into output Writing precise description of an algorithm using an easy language is most ‘essential for understanding the algorithm. An algorithm is said to be accurate and truthful only when it provides the exact required output. Lengthy procedure is subdivided into small parts as this step make it easy to solve a given problem, Every step is known as an instruction TER ori overview of computers and Mogeamning In our daily life we come aeross numerous algorithms for solving problems. We perform several routine tasks, for example, riding a bike, lifting a phone, making a telephone call, switching on the television, and so on, For example, to establish a telephonic communication between two sub- scribers the following steps are to be followed. Dial the phone number. Phone rings at the called party. Caller waits for response. Called party picks up the phone. Conversation begins between them, Release of connection. Another real-life example is to access Internet through an Internet service provider with dial-up facility. To log on to the Internet the following steps are to be followed. Another real-life example is to access Internet through an Internet service provider with dial-up facility. To log on to the Internet the following steps are to be followed. Choose the Internet service provider for accessing the Internet. Obtain a dial-up number from the service provider, Acquire IP address of the service provider. ‘Acquire login ID and password. Run the Internet browsing software. Analyzing an Algorithm ‘When one writes an algorithm, itis essential to know how to analyze the algorithm, Analyzing an algorithm refers to calculating or guessing the resources such as ‘computer memory, processing time, logie gates, and so on. In al the above factors, time is the most important beeause the program developed should be faster in pro- cessing, The analysis can also be made by reading the algorithm for logical accu- racy, tracing the algorithm, implementing it, and checking with some data and with ‘mathematical technique to confirm its accuracy. Algorithms can also be expressed in a simple method, which makes thelr implementation easier. However, this approach has a few drawbacks. It requires ‘more space and time. It is very essential to consider the factors such as time and space requirements of an algorithm. An efficient algorithm must be developed utilizing minimum system resources such as CPU time and memory. Rate of Growth In practice, frequently it is not possible to predict the execution time of an algorithm based on a simple analysis of the algorithm. The execution time depends upon the machine and the way of implementation. Timing analysis depends upon the input required. To accurately earry out the time analysis it is also very essential to know the exact directives executed by the hardware and the execution time spent for each staternent. 1.6 Flowcharts FIGURE 1.18 Start/stop Symbol A flowchart isa visual representation of the sequence of steps for solving problem. Itenlightens what comes first, second, third, and so on. A completed flowchart enables you to organize your problem into a plan of actions. Even for designing a product the designer many times draws the flowchart. Itis a working map of the final product. Ibis an easy way to solve the complex designing problems. The reader fol- lows the process quickly from the flowchart instead of going through the text. A flowchart is an alternative technique for solving a problem. Instead of doscriptive steps, we use pictorial representation for every step. It shows a sequence of operations. A flowchart is a set of symbols that indicate various 16+ Flomcnarts BB) operations in the program. For every process, there is a corresponding symbol in. the flowehart, Once an algorithm is written, its pictorial representation can be dlone using flowchart symbols. In other words, a pictorial representation ofa tex- tual algorithm is done using a flowchart. We give below some commonly used symbols in flowcharts Start and End ‘The start and end symbols indicate both the beginning and the end of the flow- chart. This symbol looks like a flat oval or is egg shaped. Fig. 1.18 shows the sym bol of start/stop. Only one flow line is combined with this kind of symbol. We write Start, Stop, or End in the symbols of this kind. Usually this symbol is used twice in a flowchart, that is, at the beginning and the end. FIGURE 1.19 Single Alternative Decision Decision or Test Symbol ‘The decision symbol is diamond shaped. This symbol is used to take one of the decisions. Depending on the condition the decision block selects one ofthe alter- natives. While solving a problem, one can take a single alternative or two or multi- ple alternatives, depending upon the situation. All these alternatives are illustrated in this section. Decision symbol with a single alternative is shown in Fig. 1.19. In cease the condition is satisfied Arue a set of statement(s) will be executed, otherwise for false, contro transfers to exit Single Alternative Decision Here more than one flow lines can be used depending upon the condition, It is usually in the form of a ‘Yes’ or ‘No’ ques- tion, with branching flow lines depending upon the answer. With a single alter- native, the flow diagram will be as per Fig, 1.19. Entry False Execution of statement (s) Exit [BB nits overview of Computers and Programming ‘Two Alternative Decisi sns_In Fig. 1.20 two alternative paths have been shown. On satisfying the condition statement(s) pertaining to action 1 will be executed, otherwise the other stat nnt(s) for action 2 will bexecuted, FIGURE. 1.20 Entry ‘Two Alternative Decisions Tre False Execution of action 1 Execution of action 2 Multiple Alternative Decisions In Fig. 1.21, multiple decision blocks are shown. Every decision block has two branches. In case the condition is satisfied FIGURE 1.21 Eniry Multiple Alternative Decisions Execution of block 1 |-—») Execution of block 2 Execution of block 3. |—+| Beis FIGURE 1.22 Connector Symbol 16+ Flowhers execution of statements of appropriate blocks takes place, otherwise next con- dition will be verified. If condition 1 is satisfied then block | statements are exe- cated. In the same way, other decision blocks are executed Connector Symbol ‘The connector symbol has to be shown in the form of a circle, It is used to establish the connection, whenever itis impossible to directly join two parts in a flowchart. Quite often, the two parts of the flowchart may be on two separate pages. In such a case, a connector can be used for joining the two parts. Only ne flow line is shown with this symbol. Only conneetor names are written Inside the symbol, that is, alphabets or numbers. Fig. 1.22 shows the connector symbol. Connector for connecting Connector that comes from. to the next block the previous block Process Symbol ‘The symbol of process block should be shown by a rectangle. Tt is usu- ally used for data handling and values are assigned to the variables in this symbol. Fig. 1.23 shows the process symbol. The operations mentioned within the ree- ‘angular block will be executed when this kind of block is entered in the flow- chart. FIGURE 1.23 Process Symbol | Kes, Aexe HEB une overiewot computer and Programing Sometimes an arrow can be used to assign the value of a varlable to another. ‘The value indicated at its head is replaced by the tail value. There are two flow lines connected with the process symbol. One line is incoming and another line goes out Loop Symbol “This symbol looks like a hexagon. This symbol is used for implementation of Joops only. Four flow lines are associated with this symbol, Two lines are used to indicate the sequence of the’ program and the remaining two are used to show the looping area, that is, from the beginning to the end For the sake of understanding, Fig. 1.24 illustrates the working of “for loop. ‘The variable J is initialized to 0 and itis to be incremented by a step of 2 until it reaches a final value 10. For every increased value of J, body of the loop is exe- cuted. This process will be continued watil the value of J reaches 10. Here the next block is shown for the repetitive operation, FIGURE 1.24 Entry For] =0 tol by stop2 Body of the for loop — Tocontinue the for loop, Exit for’ Loop Input/Output Symbol ‘The inpvtoutput symbol looks like a parallelogram as shown in Fig. 1.25. The input/output symbol is used to input and output the date. While the data i provided to the program for processing, this symbol is used. There are two flow 18+ Fowchans Hines connected with the input/output symbol, One line comes to this sym another line goes from this symbol. As por Fi ure the result is displayed on the monitor or printer. FIGURE 1.25 Symbol Delay Symbol shown in Fig. 1.26, 1.25, the complier reads the values of X, Y and in the second fig- bol of delay is just ke “AND” gate. [is used for adding delay to the process. tis associated with two lines. One is incoming and another is outgoing, as FIGURE 1.26 Delay symbol FIGURE 1.27 Manual Input symbol Manual Input Symbol ‘This is used for assigning the variable values through the keyboard, whereas data symbol the values are assigned directly without manual intervention. Fig 1.27 represents the symbol of manual input. on, the following symbols (Fig. 1.28) can be used in the flowehart and. they are parts of flowcharts. [BBB] Unies + overview of comoutes and Programming FIGURE 1.28 Some Other Symbols Used in the Flowchart | | Alternate process Predefined process Internal storage Wl Oo= Manual operation _Offf-page connector Flow lines Co S&S 2 x Punched tape Summing junction Collate Oo AV U tract Stored data AQ @ Sequential access Display Direct access storage storage 1.7. The Software Development Method Programming is @ problem-solving activity. If you are a good problem solver, you have the potential to heeome a good programmer. Therefore, ane goal of this book: isto help you improve your problei 1g ability, Problem-solving methods are covered in many subject areas, Business students lear to solve problems with a sys- tems approach while engineering and science students use the engineering and sci entific method. Programmers use the software development method. Software Development Method 1, Specify the problem requirements. 2. Analyze the problem, 1.7 + The Software Development Method [#13 3. Design the algorithm to solve the proble: 4. Implement the algorithm 5. Test and verify the completed program. 6. Maintain and update the program, PROBLEM Specifying 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. Your objective is to eliminate unimportant aspects and zero in on the root problem. This goal may not be as easy to achieve as it sounds. You may find youneed more information from the person who posed the problem. ANALYSIS Analyzing the problem involves identifying the problem (a) inputs, that is, the data ‘you have to work with; (b) outputs, that is, the desired results; and (c) any addi- tional requirements or constraints on the solution. At this stage, you should also determine the required format in which the results should be displayed (for exam- ple, as a table with specific column headings) and develop a list of problem vari- ables and their relationships. These relationships may be expressed as formulas. 1 steps 1 and 2 are not done properly, you will solve the wrong problem Read the problem statement carefully, first, to obtain a clear idea of the problem and second, to determine the inputs and outputs. You may find it helpful to underline phrases in the problem statement that identify the inputs and outputs, asin the problem statement below. Compute and display the total cost of apples given the number of pounds of apples purchased and the cost per pound of apples. Next, summarize the information contained in the underlined phrases: Problem Inputs quantity of apples purchased (in pounds) cost. per pound of apples |In dollars per pound) Problem Output totel cost of apples (in dollars) ‘Once you know the problem inputs and outputs, develop a list of formulas that specify relationships between them, The general formula Total cost = Unit cost X Number of units computes the total cost of any item purchased. Substituting the variables for our particular problem yields the formula Total cost of apples = Cost per pound x Pounds of apples [BBR] nics + overview of computers and Programming abstraction the process of modeling a Problem by extracting {he essere variables and tha relationships algorithm ast of steps for solving a problem top-down design breaking a problem into its major subprotlems ‘ard ten solang the Suiprobiems evelopment of = dotaled ist of steps to Solve a particular step inthe orginal algorithm desk checking the step-by-step simulation ofthe Computer execution ‘of an algorithm In some situations, you may need to make certain assumptions or simplifi- ‘cations to derive these relationships. This process of modeling a problem by extracting the essential variables and their relationships is called abstraction, DESIGN Designing the algorithia 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 algo- rithm solves the problem as intended. Writing the algorithin is often the most difficult part of the problem-solving process. Don't attempt to solve every detail of the problem at the beginning; instead, discipline yourself to use top-down design. In top-down design (also called divide and conquer), you fist list the Iajor steps, or subproblems, that need to be solved, Then you solve the original problem by solving each of its subproblems. Most computer algorithms consist of atleast the following subproblems. ALGORITHM FOR A PROGRAMMING PROBLEM 1. Get the data, 2. Perform the computations. 3. Display the results. Once you know the subproblems, you ean attack each one individually. For example, the perform-the-computations step may need to be broken down into a more detailed list of steps through a process called algorithm refine- ment. ‘You may be familiar with top-down design if you use an outline when writ- ing a term paper. Your first step is to ereate an outline of the major topics, ‘which you then refine by filling in subtopics for each major topic. Once the out line is complete, you begin writing the text for each subtopic. Desk checking is an important part of algorithm design that is often over- looked. To desk cheek an algorithm, you must carefully perform each algorithm step (or its refinements) just as a computer would and verify that the algorithm works as intended. You'll save time and effort if you locate algorithm errors carly in the problem-solving process. IMPLEMENTATION Implementing the algorithm: (step 4 in the software development method) invelves waiting it as a program. You must convert each algorithm step into one ina programming language. TESTING Testing and verifying the program requires testing the completed program to verify that it works as desired. Don't rely on just one test case. Run the program several times using different sots of data to make sure that it works correctly for every situation provided for in the algorithm, 18+ Applying the Software Development Method [HBS] MAINTENANCE ‘Maintaining and updating the program involves modifying & program to remove previously undetected errors and to keep it up-to-date as government regulations or company policies change. Many organizations maintain a program for five ‘years or more, often after the programmers who originally coded it have left or ‘moved on to other positions. A disciplined approach is essential if you want to create programs that are easy to read, understand, and maintain. You must follow accepted program style guidelines (which will be stressed in this book) and avoid tricks and program- ming shortcuts Caution: Failure |s Part of the Process Although having a step-by-step approach to problem solving is helpful, we must avoid jumping to the conclusion that if we follow these steps, we are guaranteed , a correct solution the first time, every time. The fact that verification is so important implies an essential truth of problem solving: The first (also the see- > ond, the third, or the twentieth) attempt at a solution may be wrong. Probably the most important distinction between outstanding problem solvers and less proficient ones is that outstanding problem solvers are not discouraged hy initial failures. Rather, they see the faulty and near-correct early solutions as a means of gaining a better understanding of the problem. One of the most inventive prob- lem solvers of all time, Thomas Edison, is noted for his positive interpretation of the thousands of failed experiments that contributed to his incredible record of inventions. His friends report that he abvays saw those failures in terms of the helpful data they yielded about what did not work. MMB) EXERCISES FOR SECTION 1.7 Self-Check 1. List the steps of the software development method. 2. Inwhich phase is the algorithm developed? In which phase do you iden- tify the problem inputs and outputs? 1.8 Applying the Software Development Method ‘Throughout this book, we use the first Ave steps of the software development method to solve programming problems. These example problems, presented as Case Studies, hegin with a problem statement. As part of the problem analysis, wwe identify the data requirements for the problem, indicating the problem ‘inputs and the desired outputs. Next, we design and refine the initial algorithm, Unit 1 © Overview of Computers and Programming, Finally, we implement the algorithm as a C program. We also provide a sample nm of the program and discuss how to test the program ‘We walk you through a sample case stody next. This example includes a run- hing commentary on the process, which you ean use as a model in solving other problems 1.8+ Applying the Software Development Method 1.35) ALGORITHM, 1. Get the distance i 2. Convert the distance to kilometers. 3. Display the distance in kilometers. Now decide whether any steps of the algorithm need further refinement or whether they are perfectly clear as stated. Step 1 (getting the data) and step 3 (displaying a value) are basic steps and fairly straightforward, but some detail m Step 2 Refinement 2.1 The distance in kilometers is 1.609 times the distance in miles We 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 2 is numbered as step 2.1 and is indented under step 2 ALGORITHM WITH REFINEMENTS 1, Get the distance in miles. Convert the distance to kilometers. 2.1 The distance in kilometers is 1.609 times the distance in miles. 3. Display the distance in kilometers Let's desk check the algorithm before going further. If step 1 gets a distance ‘of 10.0 miles, step 2.1 would convert it to 1.609 « 10,00 or 16.09 kilometers. ‘This correct result would be displayed by step 3. IMPLEMENTATION 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 requirements— that is, what memory cell names you are using and what kind of data will be stored in each memory cell. Next, convert each algorithm step into one or more C statements. If an algorithm step has been refined, you must convert the refinements, not the original step, into C statements, Figure 1.29 shows the C program along with a sample exceution, For easy identification, the program statements corresponding to algorithm steps are in color as isthe input data typed in by the program user. ‘TESTING How do you know the sample run is correct? You should always examine pro- gram results carefully to make sure that they make sense. In this run, a dis- tance of 10.0 miles is converted to 16.09 kilometers, as it should be. To verify, that the program works properly, enter a few more test values of miles. You don't need to try more than a few test cases to verify that a simple program like this is correct. ee Unit 1 * Overview of Computers and Programming MMMM EXERCISES FOR SECTION 1.8 ‘Self-Check

Vous aimerez peut-être aussi