1. Trang chủ
  2. » Công Nghệ Thông Tin

D.S. Malik – Java(TM) Programming, 4th Ed. [Course Technology, 2009]

1K 547 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Java Programming from Problem Analysis to Program Design
Tác giả D.S. Malik
Trường học Course Technology
Chuyên ngành Java Programming
Thể loại Textbook
Năm xuất bản 2010
Thành phố Boston
Định dạng
Số trang 1.021
Dung lượng 8,54 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

D.S. Malik – Java(TM) Programming, 4th Ed. [Course Technology, 2009]

Trang 3

Apago PDF Enhancer

D.S Malik

Executive Editor: Marie Lee

Acquisitions Editor: Amy Jollymore

Senior Product Manager: Alyssa Pratt

Editorial Assistant: Julia Leroux-Lindsey

Marketing Manager: Bryant Chrzan

Senior Content Project Manager: Catherine

ALL RIGHTS RESERVED No part of this work

covered by the copyright herein may be

reproduced, transmitted, stored or used in any

form or by any means graphic, electronic, or

mechanical, including but not limited to

photocopying, recording, scanning, digitizing,

taping, Web distribution, information

networks, or information storage and retrieval

systems, except as permitted under Section

107 or 108 of the 1976 United States Copyright

Act, without the prior written permission of

ISBN-13: 978-1-4390-3566-5 ISBN-10: 1-4390-3566-0 Course Technology

20 Channel Center Boston, MA 02210 USA

Cengage Learning is a leading provider of customized learning solutions with office locations around the globe, including Singapore, the United Kingdom, Australia, Mexico, Brazil, and Japan Locate your local office at:

international.cengage.com/region Cengage Learning products are represented in Canada

be trademarks or registered trademarks of their respective manufacturers and sellers.

Any fictional data related to persons or companies or URLs used throughout this book is intended for instructional purposes only.

At the time this book was printed, any such data was fictional and not belonging to any real persons or companies.

Course Technology, a part of Cengage Learning, reserves the right to revise this publication and make changes from time to time in its content without notice.

The programs in this book are for instructional purposes only They have been tested with care, but are not guaranteed for any particular intent beyond educational purposes The author and the publisher do not offer any warranties or representations, nor

do they accept any liabilities with respect to the programs.

Trang 4

Apago PDF Enhancer

TO

My Daughter

Shelly Malik

Trang 5

Apago PDF Enhancer

Trang 6

Apago PDF Enhancer

1 An Overview of Computers and Programming Languages 1

3 Introduction to Objects and Input/Output 107

6 Graphical User Interface (GUI) and Object-Oriented Design (OOD) 295

APPENDIX E Answers to Odd-Numbered Exercises 949

B R I E F C O N T E N T S

Trang 7

An Overview of the History of Computers 2

Internet, World Wide Web, Browser, and Java 13 Programming with the Problem Analysis–Coding–

Trang 8

Apago PDF Enhancer

Arithmetic Operators and Operator Precedence 36

Allocating Memory with Named Constants and Variables 48

Declaring and Initializing Variables 55

Debugging: Understanding Error Messages 91

Trang 9

Apago PDF Enhancer

INTRODUCTION TO OBJECTS AND INPUT/OUTPUT 107

Using Predefined Classes and Methods in a Program 112 Dot Between Class (Object) Name and Class Member:

Using Dialog Boxes for Input/Output 132 Formatting the Output Using the String Method format 139

Trang 10

Apago PDF Enhancer

Comparing if else Statements with a Series

Conditional Operator (? :) (Optional) 192

Avoiding Bugs by Avoiding Partially Understood

Programming Example: Cable Company Billing 201

CONTROL STRUCTURES II: REPETITION 225

while Looping (Repetition) Structure 227

More on Expressions in while Statements 247 Programming Example: Fibonacci Number 248 for Looping (Repetition) Structure 254 Programming Example: Classify Numbers 259 do while Looping (Repetition) Structure 263 Choosing the Right Looping Structure 268

5

Table of Contents | ix

Trang 11

Apago PDF Enhancer

Implementing Classes and Operations 338 Primitive Data Types and the Wrapper Classes 338

Trang 12

Apago PDF Enhancer

Programming Example: Largest Number 373

Primitive Data Type Variables as Parameters 379

Reference Variables of the String Type as Parameters:

Primitive Type Wrapper Classes as Parameters 389 Scope of an Identifier Within a Class 390 Method Overloading: An Introduction 393 Programming Example: Data Comparison 395 Avoiding Bugs: One-Piece-at-a-Time Coding 406 Avoiding Bugs: Using ‘‘Stubs’’ as Appropriate 407

USER-DEFINED CLASSES AND ADTs 425

Unified Modeling Language Class Diagrams 432 Variable Declaration and Object Instantiation 433

Assignment Operator and Classes: A Precaution 436

Definitions of the Constructors and Methods

8

Table of Contents | xi

Trang 13

Apago PDF Enhancer

static Variables (Data Members) of a Class 461

Debugging—Designing a Class and Documenting

Programming Example: Candy Machine 479

Alternate Ways to Declare an Array 513

Specifying Array Size during Program Execution 515 Array Initialization during Declaration 516 Arrays and the Instance Variable length 516 Processing One-Dimensional Arrays 517 Array Index Out of Bounds Exception 522 Declaring Arrays as Formal Parameters to Methods 522 Assignment Operator, Relational Operators, and Arrays:

9

Trang 14

Apago PDF Enhancer

Searching an Array for a Specific Item 530

Arrays of Objects of Other Classes 534 Arrays and Variable Length Parameter List (Optional) 539

Two-Dimensional Array Initialization During Declaration 552 Processing Two-Dimensional Arrays 553 Passing Two-Dimensional Arrays as Parameters to Methods 557

Programming Example: Code Detection 563 Programming Example: Text Processing 567

Primitive Data Types and the class Vector 578 Vector Objects and the foreach Loop 578

Trang 15

HANDLING EXCEPTIONS AND EVENTS 673

Handling Exceptions Within a Program 674 Java’s Mechanism of Exception Handling 677

More Examples of Exception Handling 693 class Exception and the Operator instanceof 696 Rethrowing and Throwing an Exception 699

Creating Your Own Exception Classes 708

Trang 16

Converting an Application Program to an Applet 758

12

13

Table of Contents | xv

Trang 17

APPENDIX A: JAVA RESERVED WORDS 891

APPENDIX B: OPERATOR PRECEDENCE 893

APPENDIX C: CHARACTER SETS 897

ASCII (American Standard Code for Information Interchange), the First 128 Characters of the

EBCDIC (Extended Binary Coded Decimal

14

Trang 18

Apago PDF Enhancer

APPENDIX D: ADDITIONAL JAVA TOPICS 901

Binary (Base 2) Representation of a Nonnegative Integer 901 Converting a Base 10 Number to a Binary Number (Base 2) 901 Converting a Binary Number (Base 2) to Base 10 903 Converting a Binary Number (Base 2) to Octol (Base 8)

Executing Java Programs Using the Command-Line

Formatting the Output of Decimal Numbers Using

Programming Example: The Rock, Paper,

APPENDIX E: ANSWERS TO ODD-NUMBERED

Trang 20

Apago PDF Enhancer

Welcome to Java Programming: From Problem Analysis to Program Design, Fourth Edition Designedfor a first Computer Science (CS1) Java course, this text will provide a breath of fresh air to youand your students The CS1 course serves as the cornerstone of the Computer Science curricu-lum My primary goal is to motivate and excite all programming students, regardless of their level.Motivation breeds excitement for learning Motivation and excitement are critical factors thatlead to the success of the programming student This text is the culmination and development of

my classroom notes throughout more than fifty semesters of teaching successful programming.Warning:This text can be expected to create a serious reduction in the demand for program-ming help during your office hours Other side effects include significantly diminished studentdependency on others while learning to program

The primary focus in writing this text is on student learning Therefore, in addition to clearexplanations, we address the key issues that otherwise impede student learning For example, acommon question that arises naturally during an early programming assignment is: ‘‘Howmany variables and what kinds are needed in this program?’’ We illustrate this important andcrucial step by helping students learn why variables are needed and how data in a variable ismanipulated Next students learn that the analysis of the problem will spill the number andtypes of the variables Once students grasp this key concept, control structures, (selection andloops) become easier to learn The second major impediment in learning programming isparameter passing We pay special attention to this topic First students learn how to usepredefined methods and how actual and formal parameters relate Next students learn aboutuser-defined methods They see visual diagrams that help them learn how methods are calledand how formal parameters affect actual parameters Once students have a clear understanding

of these two key concepts, they readily assimilate advanced topics

The topics are introduced at a pace that is conducive to learning The writing style is friendly,engaging, and straightforward It parallels the learning style of the contemporary CS1 student.Before introducing a key concept, the student learns why the concept is needed, and then seesexamples illustrating the concept Special attention is paid to topics that are essential inmastering the Java programming language and in acquiring a foundation for further study

of computer science

Other important topics include debugging techniques and techniques for avoiding ming bugs When a beginner compiles his/her first program and sees that the number oferrors exceeds the length of this first program, he/she becomes frustrated by the plethora oferrors, only some of which can be interpreted To ease this frustration and help students learn

program-to produce correct programs, debugging and bug avoidance techniques are presented atically throughout the text

system-P R E F A C E T O T H E F O U R T H E D I T I O N

Trang 21

Apago PDF Enhancer

Changes In The Fourth Edition

In the fourth edition, the main changes are:

• In the fourth edition, throughout the text sections on debugging techniques andtechniques on avoiding programming bugs are included

• Chapter 10 of the third edition, which includes searching and sorting algorithms, isnow Chapter 14 Sequential search algorithm and theclass Vector, which werecovered in Chapter 10, have been moved to Chapter 9 The additional methods ofthe class String, which were covered in Chapter 10 of the third edition, arenow covered in Chapter 3 The OOD version of the programming example ofChapter 14 is available on the Web site and the CD accompanying this book.Furthermore, Chapter 14 also contains bubble sort and quick sort algorithms, whichare provided on the Web site and the CD accompanying this book

• Chapters 11, 12, 13, and 14 in the third edition are now Chapters 10, 11, 12, and 13,respectively, in the fourth edition

• In the third edition, Chapter 7 contains user-defined classes so that primitive type valuescan be passed as objects and methods can manipulate and pass those values back to thecalling environment In the fourth edition, this discussion is taken out of Chapter 7 andput in a separate section, entitled ‘‘Chapter_7_PassingPrimitiveTypeAsObjects’’ Thissection is available on the Web site and the CD accompanying this book Furthermore,

as suggested by the reviewers, additional examples are included in this chapter

• The fourth addition contains more than 30 new programming exercises

• In Chapter 5, the Programming Example, Checking Account Balance, is available onthe Web site and the CD accompanying this book

• In Appendix D, a new section on how to create Java style documentation of defined classes has been added

user-These changes were implemented based on comments from the text reviewers of the thirdedition The source code and the programming exercises are developed and tested using Java6.0 and the version of Java 7.0 available at the time the book was being typeset

Approach

Once conceived as a Web programming language, Java slowly but surely found its way intoclassrooms where it now serves as a first programming language in computer science curricula(CS1) Java is a combination of traditional style programming—programming with a non-graphical user interface—and modern style programming with a graphical user interface(GUI) This book introduces you to both styles of programming After giving a briefdescription of each chapter, we discuss how to read this book

Chapter 1 briefly reviews the history of computers and programming languages The readercan quickly skim and become familiar with some of the hardware and software components ofthe computer This chapter also gives an example of a Java program and describes how a Java

Trang 22

is one of the most important classes in Java This chapter introduces this class and explains howvarious methods of this class can be used to manipulate strings Because input/output is funda-mental to any programming language, it is introduced early, and is covered in detail in Chapter 3.Chapters 4 and 5 introduce control structures used to alter the sequential flow of execution.Java is equipped with powerful yet easy-to-use graphical user interface (GUI) components tocreate user-friendly graphical programs Chapter 6 introduces various GUI components andgives examples of how to use these components in Java application programs Because Java is

an object-oriented programming language, the second part of Chapter 6 discusses and givesexamples of how to solve various problems using object-oriented design methodology.Chapter 7 discusses user-defined methods Parameter passing is a fundamental concept in anyprogramming language Several examples, including visual diagrams, help readers understandthis concept It is recommended that readers with no prior programming background spendextra time on this concept

Chapter 8 discusses user-defined classes In Java, a class is an important and widely usedelement It is used to create Java programs, group related operations, and it allows users tocreate their own data types This chapter uses extensive visual diagrams to illustrate howobjects of classes manipulate data

Chapter 9 describes arrays This chapter also introduces variable length formal parameter lists

In addition, this chapter introduces foreach loops and explains how this loop can be used toprocess the elements of an array This chapter also discusses the sequential searching algorithmand theclass Vector

Inheritance is an important principle of object-oriented design It encourages code reuse.Chapter 10 discusses inheritance, and gives various examples to illustrate how classes arederived from existing classes In addition, this chapter also discusses polymorphism, abstractclasses, inner classes, and composition

An occurrence of an undesirable situation that can be detected during program execution iscalled an exception For example, division by zero is an exception Java provides extensivesupport for handing exceptions Chapter 11 shows how to handle exceptions in a program.Chapter 11 also discusses event handling, which was introduced in Chapter 6 Chapter 12picks up the discussion of GUI components started in Chapter 6 This chapter introducesadditional GUI components and discusses how to create applets

Preface to the Fourth Edition | xxi

Trang 23

Apago PDF Enhancer

Chapter 13 introduces recursion Several examples illustrate how recursive methods execute.Chapter 14 discusses a binary search algorithm as well as bubble sort, selection sort, insertionsort, and quick sort algorithms The sorting algorithms: bubble sort and quick sort areprovided on the Web site and the CD accompanying this book

Appendix A lists the reserved words in Java Appendix B shows the precedence andassociativity of the Java operators Appendix C lists the ASCII (American Standard Codefor Information Interchange) portion of the Unicode character set as well as the EBCDIC(Extended Binary Code Decimal Interchange) character set

Appendix D contains additional topics in Java The topics covered are converting a base 10number to binary (base 2) number and vice versa, converting a number from base 2 to base 8(base 16) and vice versa, how to compile and execute a Java program using command linestatements, how to create Java style documentation of the user-defined classes, how to createpackages, how to use user-defined classes in a Java program, and enum type Appendix Egives answers to all the odd-numbered exercises in the text

How To Use This Book

Java is a complex and very powerful language In addition to traditional (non-GUI) ming, Java provides extensive support for creating programs that use a graphical user interface(GUI) Chapter 3 introduces graphical input and output dialog boxes Chapter 6 introducesmost commonly used GUI components such as labels, buttons, and text fields More extensivecoverage of GUI components is provided in Chapter 12

program-This book can be used in two ways One way is an integrated approach in which readers learnhow to write both non-GUI and GUI programs as they learn basic programming conceptsand skills The other approach focuses on illustrating fundamental programming conceptswith non-GUI programming first, and later incorporating GUI components The recom-mended chapter sequence for each of these approaches is as follows:

• Integrated approach:Study all chapters in sequence

• Non-GUI first, then GUI:Study Chapters 1–5 in sequence Then study Chapters7–11 and Chapters 13 and 14 This approach initially skips Chapters 6 and 12, theprimary GUI chapters After studying Chapters 1–5, 7–11, 13, and 14, the reader cancome back to study Chapters 6 and 12, the GUI chapters Also note that Chapter 14can be studied after Chapter 9

If you choose the second approach, it should also be noted that the Programming Examples inChapters 8 and 10 are developed first without any GUI components, and then the programsare extended to incorporate GUI components Also, if Chapter 6 is skipped, the reader can skipthe event handling part of Chapter 11 Chapter 13 (recursion) contains two ProgrammingExamples: one creates a non-GUI application program, while the other creates a program thatuses GUI If you skip Chapters 6 and 12, you can skip the GUI part of the ProgrammingExamples in Chapters 8, 10, 11, and 13 Once you have studied Chapter 6 and 12, you canstudy the GUI part of the Programming Examples of Chapters 8, 10, 11, and 13

Trang 24

Apago PDF Enhancer

Figure 1 shows a chapter dependency diagram for this book Solid arrows indicate that thechapter at the beginning of the arrow is required before studying the chapter at the end of thearrow A dotted arrow indicates that the chapter at the beginning of the arrow is not essential

to studying the chapter at the end of the dotted arrow

A dotted arrow means that the chapter is not essential to studying the following chapter.

Chapter 11

Chapter 12

Chapter 13

FIGURE 1 Chapter dependency diagram

All source code and solutions have been written, compiled, and quality assurance testedwith Java 6.0 and the version of Java 7.0 available at the time the book was being typeset

Preface to the Fourth Edition | xxiii

Trang 25

Apago PDF Enhancer

Four-color interior design shows accurate code and related comments.

Trang 27

Numbered Examples illustrate the key concepts with their relevant code The programming code in these examples is followed by a Sample Run An explanation then follows that describes what each line in the code does.

Trang 29

Apago PDF Enhancer

complete programs featured in each chapter These examples include the accurate, concrete stages of Input, Output, Problem Analysis and Algorithm Design, and a

Complete Program Listing.

Trang 30

Apago PDF Enhancer

Exercises further reinforce learning and ensure that students have, in fact, mastered the material.

Trang 31

Apago PDF Enhancer

students to write Java programs with

a specified outcome.

Trang 32

Electronic Instructor’s Manual

The Instructor’s Manual that accompanies this textbook includes:

• Additional instructional material to assist in class preparation, including suggestionsfor lecture topics

• Solutions to all the end-of-chapter materials, including the Programming Exercises

This textbook is accompanied by ExamView, a powerful testing software package thatallows instructors to create and administer printed, computer (LAN-based), and Internetexams ExamView includes hundreds of questions that correspond to the topics covered inthis text, enabling students to generate detailed study guides that include page references forfurther review These computer-based and Internet testing components allow students totake exams at their computers, and save the instructor time because each exam is gradedautomatically

PowerPoint Presentations

This book comes with Microsoft PowerPoint slides for each chapter These slides are included as

a teaching aid for classroom presentations, either to make available to students on the networkfor chapter review, or to be printed for classroom distribution Instructors can add their ownslides for additional topics that they introduce to the class

Distance Learning

Cengage Course Technology is proud to present online courses in WebCT and Blackboard

to provide the most complete and dynamic learning experience possible For more tion on how to bring distance learning to your course, contact your local Cengage CourseTechnology sales representative

informa-S U P P L E M E N T A L R E S O U R C E S

Trang 34

I owe a great deal to the following reviewers, who patiently read each page of every chapter

of the current version and made critical comments to improve on the book: Atef Bader,DePaul University; Rajwant Gill, Anne Arundel Community College; Gerard Gordon,DePaul University; Jenneth Honeycutt, Fayetteville Technical Community College; andJohn Mill, Spokane Falls Community College Additionally, I would like to thank thereviewers of the proposal package: Lemond Hall, South Georgia Technical College andHemand Pendharkar, Worcester State College The reviewers will recognize that theirsuggestions have not been overlooked and, in fact, made this a better book

Next, I express thanks to Amy Jollymore, Acquisitions Editor, for recognizing the importanceand uniqueness of this project All this would not have been possible without the carefulplanning of Senior Product Manager Alyssa Pratt I extend my sincere thanks to Alyssa, as well

as to Senior Content Project Manager, Catherine DiMassa I also thank Tintu Thomas ofIntegra Software Services for assisting us in keeping the project on schedule I would like tothank Chris Scriver and Serge Palladino of the QA department of Course Technology forpatiently and carefully proofreading the text, testing the code, and discovering typos and erros

I am thankful to my parents for their blessings

Finally, I am thankful to the support of my wife Sadhana, and especially my daughter Shelly,

to whom this book is dedicated They cheered me up whenever I was overwhelmed duringthe writing of this book

We welcome any comments concerning the text Comments may be forwarded to thefollowing e-mail address:malik@creighton.edu

D.S Malik

A C K N O W L E D G M E N T S

Trang 35

Apago PDF Enhancer

Trang 36

n Learn about different types of computers

n Explore the hardware and software components of a computer system

n Learn about the language of a computer

n Learn about the evolution of programming languages

n Examine high-level programming languages

n Discover what a compiler is and what it does

n Examine how a Java program is processed

n Learn about the Internet and World Wide Web

n Learn what an algorithm is and explore problem-solving techniques

n Become familiar with structured and object-oriented programming design methodologies

Trang 37

An Overview of the History of Computers

The first device known to carry out calculations was the abacus The abacus was invented

in Asia but was used in ancient Babylon, China, and throughout Europe until the latemiddle ages The abacus uses a system of sliding beads on a rack for addition andsubtraction In 1642, the French philosopher and mathematician Blaise Pascal inventedthe calculating device called the Pascaline It had eight movable dials on wheels that couldcalculate sums up to eight figures long Both the abacus and Pascaline could perform onlyaddition and subtraction operations Later in the seventeenth century, Gottfried vonLeibniz invented a device that was able to add, subtract, multiply, and divide In 1819,Joseph Jacquard, a French weaver, discovered that the weaving instructions for his loomscould be stored on cards with holes punched in them While the cards moved throughout theloom in sequence, needles passed through the holes and picked up threads of the correct colorand texture A weaver could rearrange the cards and change the pattern being woven Inessence, the cards programmed a loom to produce patterns in cloth The weaving industryseems to have little in common with the computer industry However, the idea of storinginformation by punching holes on a card turned out to be of great importance in the laterdevelopment of computers

In the early and mid-1800s, Charles Babbage, an English mathematician and physicalscientist, designed two calculating machines—the difference engine and the analyticalengine The difference engine could automatically perform complex operations, such assquaring numbers Babbage built a prototype of the difference engine, but the actualdevice was never produced The analytical engine’s design included input device,memory storage, a control unit that allowed processing instructions in any sequence,and output devices However, the designs remained in blueprint stage Most of Babbage’swork is known through the writings of the colleague Ada Augusta, Countess of Lovelace.Augusta is considered to be the first computer programmer

At the end of the 19th century, U.S Census officials needed help in accurately tabulatingthe census data Herman Hollerith invented a calculating machine that ran on electricityand used punched cards to store data Hollerith’s machine was immensely successful

Trang 38

In 1956, the invention of the transistors resulted in smaller, faster, more reliable, and moreenergy-efficient computers This era also saw the emergence of the software developmentindustry with the introduction of FORTRAN and COBOL, two early programminglanguages In the next major technological advancement, transistors were replaced by tinyintegrated circuits or ‘‘chips.’’ Chips are smaller and cheaper than transistors and cancontain thousands of circuits on a single chip They give computers tremendous proces-sing speed.

In 1970, the microprocessor, an entire CPU on a single chip, was invented In 1977,Stephen Wozniak and Steven Jobs designed and built the first Apple computer in theirgarage In 1981, IBM introduced its personal computer (PC) In the 1980s, clones of theIBM PC made the personal computer even more affordable By the mid-1990s, peoplefrom many walks of life were able to afford them Computers continue to become fasterand less expensive as technology advances

Modern-day computers are very powerful, reliable, and easy to use They can acceptspoken-word instructions and imitate human reasoning through artificial intelligence.Expert systems assist doctors in making diagnoses Mobile computing applications aregrowing significantly Using hand-held devices, delivery drivers can access global posi-tioning satellites (GPS) to verify customer locations for pickups and deliveries Cellphones can check your e-mail, make airline reservations, see how stocks are performing,and access your bank accounts

Although there are several categories of computers, such as mainframe, midsize, andmicro, all computers share some basic elements

Elements of a Computer System

A computer is an electronic device capable of performing commands The basic mands that a computer performs are input (get data), output (display results), storage, andperformance of arithmetic and logical operations

com-1

Elements of a Computer System | 3

Trang 39

Apago PDF Enhancer

In today’s market, personal computers are sold with descriptions such as a Pentium 4Processor 2.80 GHz, 1 GB RAM, 100 GB HD, VX750 17’’ Silver Flat CRT Color Monitor,preloaded with software such as an operating system, games, encyclopedias, and applicationsoftware such as word processors or money management programs These descriptionsrepresent two categories: hardware and software Items such as ‘‘Pentium 4 Processor 2.80GHz, 1 GB RAM, 100 GB HD, VX750 17’’ Silver Flat CRT Color Monitor’’ fall into thehardware category; items such as ‘‘operating system, games, encyclopedias, and applicationsoftware’’ fall into the software category Let’s look at the hardware first

Hardware

Major hardware components include the central processing unit (CPU); main memory(MM), also called random access memory (RAM); input/output devices; and secondarystorage Some examples of input devices are the keyboard, mouse, and secondary storage.Examples of output devices are the monitor, printer, and secondary storage

CENTRAL PROCESSING UNIT AND MAIN MEMORY

The central processing unit (CPU) is the ‘‘brain’’ of the computer and the single mostexpensive piece of hardware in a computer The more powerful the CPU, the faster thecomputer Arithmetic and logical operations are carried out inside the CPU Figure 1-1(a)shows some hardware components

Main memory, or random access memory (RAM), is connected directly to the CPU.All programs must be loaded into main memory before they can be executed Similarly,

Central Processing

Unit (CPU)

Main Memory

Secondary Storage

Input Device

Output Device

(b) (a)

2001 2000

1001

1000 54

A

.

.

.

.

Main Memory

FIGURE 1-1 Hardware components of a computer and main memory

Trang 40

Today’s computers come with main memory consisting of millions to billions of cells.Although Figure 1-1(b) shows data stored in cells, the content of a cell can be either aprogramming instruction or data Moreover, this figure shows the data as numbers andletters However, as explained later in this chapter, main memory stores everything assequences of0s and1s The memory addresses are also expressed as sequences of0s and1s.

SECONDARY STORAGE

Because programs and data must be stored in main memory before processing, andbecause everything in main memory is lost when the computer is turned off, informationstored in main memory must be transferred to some other device for longer-term storage

A device that stores longer-term information (unless the device becomes unusable or youchange the information by rewriting it) is called secondary storage To be able totransfer information from main memory to secondary storage, these components must beconnected directly to each other Examples of secondary storage are hard disks, floppydisks, flash memory, ZIP disks, CD-ROMs, and tapes

INPUT/OUTPUT DEVICES

For a computer to perform a useful task, it must be able to take in data and programs anddisplay the results of the manipulation of the data The devices that feed data andprograms into computers are called input devices The keyboard, mouse, and secondarystorage are examples of input devices The devices that the computer uses to display andstore results are called output devices A monitor, printer, and secondary storage areexamples of output devices Figure 1-2 shows some input and output devices

1

FIGURE 1-2 Some input and output devices

Elements of a Computer System | 5

Ngày đăng: 23/12/2013, 15:44

TỪ KHÓA LIÊN QUAN

w