unit -1(problem solving and program desing in c unit -1

Upload: syam5491983

Post on 04-Jun-2018

217 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/13/2019 Unit -1(Problem solving and program desing in c UNIT -1

    1/27

    1Overview of

    Computers andProgramming

    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 aC program

    To learn how to solve a programming problem in acareful, disciplined way

    To understand and appreciate ethical issues related tothe use of computers and programming

    U IT

  • 8/13/2019 Unit -1(Problem solving and program desing in c UNIT -1

    2/27

    Introdu!tion

    uters are machines whichoutput information can

    data of all kinds:aphics, and sound, to

    The computerram s role intechnology is

    essential! without a list of instructions to follow, the computer is virtually useless"#rogramming languages allow us to write those programs and thus to communicatewith computers"

    $ou are about to begin the study of computer science using one of the mostversatile programming languages available today: the C language" This chapterintroduces you to the computer and its components and to the ma%or categories ofprogramming languages" &t discusses how C programs are processed by a computer" &also describes a systematic approach to solving programming problems called thesoftware 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 tanasoffand Clifford -erry at &owa .tate /niversity" tanasoff designed his computer toassist graduate students in nuclear physics with their mathematical computations"

    The first large0scale, general0purpose electronic digital computer, called the2& 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 2& Cwas used to compute ballistics tables, predict the weather, and make atomic energycalculations"

    These early computers used vacuum tubes as their basic electronic component"Technological advances in the design and manufacture of electronic components ledto new generations of computers that were considerably smaller, faster, and lessexpensive than previous ones"

  • 8/13/2019 Unit -1(Problem solving and program desing in c UNIT -1

    3/27

    !omputer !%ip&mi!ropro!essor!%ip' a siliconchip containing thecircuitry for a computerprocessor

    1"1 lectronic Computers Then and 2ow

    /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 chip78 ig" 1 "19, which is less than one0fourth the si e of a standard postage stamp" Theiraffordability and small si:e enable computer chips to be installed in watches, cellphones,;#. systems, cameras, home appliances, automobiles, and, of course, computers"

    argereal0time transaction processing systems, such as T

  • 8/13/2019 Unit -1(Problem solving and program desing in c UNIT -1

    4/27

    Chapter 1 ?verview of Computers and #rogramming

    (I)URE "#*

    7a9 *esktop Computer, iaptop" 7@ Aewlett0#ackardCompany9" 7c9 i#ad" 7@ *" AurstB lamy9" 7d9 ndroid phone, >; Thrill 3;" 7@ AandoutB

  • 8/13/2019 Unit -1(Problem solving and program desing in c UNIT -1

    5/27

    1"= Computer Aardware

    The elements of a computer system fall into two ma%or categories: hardware andsoftware" Aardware is the equipment used to perform the necessary computationsand includes the central processing unit 7C#/9, monitor, keyboard, mouse, printer,and speakers" .oftware consists of the programs that enable us to solve problemswith 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 programinstructions as long binary numbers 7sequences of )s and 1s9" Aigh0level pro0gramming languages such as C make programming much easier"

    "#* Computer Hardware*espite significant variations in cost, si e, and capabilities, modern computersresemble one another in many basic ways" ssentially, most consist of the followingcomponents:

  • 8/13/2019 Unit -1(Problem solving and program desing in c UNIT -1

    6/27

    Chapter 1 ?verview of Computers and #rogramming

    (I)URE "#.

    Components of a Computer

    .econdary storage

    &nput devices

  • 8/13/2019 Unit -1(Problem solving and program desing in c UNIT -1

    7/27

    1"= Computer Aardware

  • 8/13/2019 Unit -1(Problem solving and program desing in c UNIT -1

    8/27

    Chapter 1 ?verview of Computers and #rogramming

    (I)URE "#1

    .econdary .torage

  • 8/13/2019 Unit -1(Problem solving and program desing in c UNIT -1

    9/27

    1"= Computer Aardware

    TAB2E "#" Terms /sed to Iuantify .torage Capacities

    Term bbreviation quivalent to Comparison to #ower of 1)

    -yte - E bits

    Jilobyte J- 1,)=3 7= 1 ) 9 bytes K 1) (

  • 8/13/2019 Unit -1(Problem solving and program desing in c UNIT -1

    10/27

    Chapter 1 ?verview of Computers and #rogramming

    that instruction" 2ext, the C#/ performs the actual manipulation, or processing, of thedata it retrieved" The C#/ stores the results in main memory"

    The C#/ can perform such arithmetic operations as addition, subtraction, mul0tiplication, and division" The C#/ can also compare the contents of two memorycells 7for example, 5hich contains the larger valueL re the values equalL9 andmake decisions based on the results of that comparison"

    .ome computers have multiple C#/s 7 multiprocessors 9 or a multi0core C#/" Thesecomputers are capable of faster speeds because they can process different sets ofinstructions at the same time"

    Input3Output 4evi!es

    5e use inputBoutput 7&B?9 devices to communicate with the computer" .pecifically, theyallow 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 sentto main memory and is also displayed on the monitor at the position of the cursor , amoving place marker 7often a blinking line or rectangle9" computer keyboard has keysfor letters, numbers, and punctuation marks plus some extra keys for performing specialfunctions" The twelve function keys along the top row of the keyboard are labeled 81through 81=" The activity performed when you press a function key depends on the pro0gram currently being executed! that is, pressing 81 in one program will usually not pro0duce the same results as pressing 81 in another program" ?ther special keys enable youto 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 usedto select an operation"

  • 8/13/2019 Unit -1(Problem solving and program desing in c UNIT -1

    11/27

    (I)URE "#6

    >ocal rea2etwork

    4S2 !onne!tion&digita$ su+s!ri+er$ine' a high0speed&nternet connection thatuses a telephone lineand does not interferewith simultaneous voicecommunication on thesame line

    1"= Computer Aardware

    devices in a building are connected by cables or a wireless network, allowing them toshare information and resources such as printers, scanners, and secondary stor0age devices 7 8ig" 1"H 9" computer that controls access to a secondary storage device sucas a large hard disk is called a file server "

    >ocal area networks can be connected to other > 2s using the same tech0nology as telephone networks" Communications over intermediate distances usephone lines, fiber0optics cables or wireless technology, and long0range com0munications use either phone lines or microwave signals that may be relayed bysatellite 78ig" 1"E9"

    network that links many individual computers and local area networks over alarge geographic area is called a wide area network 75 29 " The most well0known5 2 is the &nternet, a network of university, corporate, government, and public0access networks" The &nternet is a descendant of the computer network designedby the /"." *efense *epartment s 1'4' F# net pro%ect" The goal of the pro%ectwas to create a computer network that could continue to operate even if partiallydestroyed" The most widely used aspect of the &nternet is the 5orld 5ide 5eb75559, the universe of &nternet0accessible resources that are navigable throughthe use of a graphical user interface 7;/&9 "

    &f you have a computer with a modem, you can connect to the informationsuperhighway through a telephone line, television or fiber0optic cable, or through

    wireless or satellite communications" modem 7modulatorBdemodulator9 convertsbinary computer data into audio tones that can be transmitted to another computerover a normal telephone circuit" t the computer on the receiving end, anothermodem converts the audio tones back to binary data"

    arly modems for telephone lines transmitted at only ()) baud 7()) bits persecond9" Today s modems transmit over 6),))) bits per second, or if you have adigital subscriber line 7 *.> connection 9 or fiber0optics telephone line, the associated

  • 8/13/2019 Unit -1(Problem solving and program desing in c UNIT -1

    12/27

    Chapter 1 ?verview of Computers and #rogramming

    (I)URE "#7

    5ide rea 2etwork with .atellite Felays of 29

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

  • 8/13/2019 Unit -1(Problem solving and program desing in c UNIT -1

    13/27

    1"( Computer .oftware

    "#. Computer Software&n the previous section, we surveyed the components of a computer system, compo0nents referred to collectively as hardware" 5e also studied the fundamental opera0tions that allow a computer to accomplish tasks: repeated fetching and executionof instructions" &n this section we focus on these all0important lists of instructionscalled computer programs or computer software" 5e will consider first the softwarethat makes the hardware friendly to the user" 5e will then look at the various levelsof computer languages in which software is written and at the process of creatingand running a new program"

    Operating S-stem

    The collection of computer programs that control the interaction of the user andomputer hardware is

    d the operating system" The operating sys0of a computer iscompared to the

    uctor of anestra, for it is the

    ware that isonsible for directingcomputer operations

    managing allputer resources"

    ly part of theating system isd permanently in a0only memory 7F?

  • 8/13/2019 Unit -1(Problem solving and program desing in c UNIT -1

    14/27

    Chapter 1 ?verview of Computers and #rogramming

    TAB2E "#* 5idely /sed ?perating .ystem 8amiliesCategori ed by /ser &nterface Type

    Command-Line Interface Gra !ical "ser Interface

    /2&O

  • 8/13/2019 Unit -1(Problem solving and program desing in c UNIT -1

    15/27

    1.3 ComputerSoftware

    soft ?ffice ccess

    "

    mputer 2anguages

    loping newware requires writingof instructions for a

    puter toute" Aowever,

    ware developersy write in theuage directly under0d by a computer, this machine

    uage is a collectionbinary num0

    nother drawback ofhine language is that it

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

  • 8/13/2019 Unit -1(Problem solving and program desing in c UNIT -1

    16/27

    Chapter 1 ?verview of Computers and #rogramming

    TAB2E "#. anguage #rogram 8ragment and &ts ssembly>anguage quivalent

    anguage ssembly >anguage

    )))))))1 )))1)1)1 **

    ))))))1) )))1)11) ** -

    ))))))11 ))11)1)1 .T

    )))))1)) )111)111 A>T

    )))))1)1 L L

    )))))11) L - L

    to the somewhat more readable assembly language, a language in which computer operations are represented by mnemonic codes rather than binary numbers andvariables can be given names rather than binary memory addresses" Table 1"(shows a tiny machine language program fragment that adds two numbers and theequivalent fragment in assembly language" 2otice that each assembly languageinstruction corresponds to exactly one machine instruction: The assembly languagememory 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 withaddresses )))))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 algebraicexpressions and symbols taken from nglish" 8or example, the machineBassemblylanguage program fragment shown in Table 1"( would be a single statement in ahigh0level language:

    a # a $ %&

    This statement means Madd the values of variables a and %, and store the result invariable a 7replacing a s previous value9"N

    There are many high0level languages available" Table 1"3 lists some of themost widely used ones along with the origin of their names and the applicationareas that first populari ed them" lthough programmers find it far easier to

    express problem solutions in high0level languages, there remains the problemthat computers do 2?T understand these languages" Thus, before a high0levellanguage program can be executed, it must first be translated into the target com0puter s machine language" The program that does this translation is called a com0piler " 8igure 1"11 illustrates the role of the compiler in the process of developing

  • 8/13/2019 Unit -1(Problem solving and program desing in c UNIT -1

    17/27

    1"( Computer .oftware

    TAB2E "#/ Aigh0>evel >anguages

    >anguage pplication rea ?rigin of 2ame

    8?FTF 2 .cientific programming (or mula tran slation

    C?-?> -usiness data processing Co mmon B usiness0 Oriented 2 anguage>&.# rtificial &ntelligence 2is t processing

    C .ystems programming #redecessor language was named -

    #rolog rtificial &ntelligence 2og ic pro gramming

    da Feal0time distributed systems Ada ugusta -yron collaborated with nineteenth0centurycomputer pioneer Charles -abbage

    .malltalk ;raphical user interfaces! ?b%ects MtalkN to one another via messagesob%ect0oriented programming

    CPP .upports ob%ects and ob%ect0oriented &ncremental modification of C 7PP is the C increment operator9programming

    +ava .upports 5eb programming and ?riginally named M?akNprogramming ndroid applications

    and testing a high0level language program" -oth the input to and the output fromthe compiler 7when it is successful9 are programs" The input to the compiler is asource file containing the text of a high0level language program" The softwaredeveloper creates this file by using a word processor or editor" The format of thesource file is text, which means that it is a collection of character codes" 8or exam0ple, 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 ssyntax 7grammar9 rules" &f the program is syntactically correct, the compiler saves inan ob%ect file the machine language instructions that carry out the program spurpose" 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 itto a printer, display it on your monitor, or try to work with it in a word proces0sor because it will appear to be meaningless garbage to a word processor, printer, ormonitor" &f the source program contains syntax errors, the compiler lists theseerrors but does not create an ob%ect file" The developer must return to the wordprocessor, correct the errors, and recompile the program"

    lthough an ob%ect file contains machine instructions, not all of the instruc0tions are complete" Aigh0level languages provide the software developer with manynamed chunks of code for operations that the developer will likely need" lmost allhigh0level language programs use at least one of these chunks of code called func0tions that reside in other ob%ect files available to the system" The linker programcombines these prefabricated functions with the ob%ect file, creating a complete

  • 8/13/2019 Unit -1(Problem solving and program desing in c UNIT -1

    18/27

    Chapter 1 ?verview of Computers and #rogramming

    (I)URE "#""

    ntering, Translating, and Funning a Aigh0>evel >anguage #rogram 7 #rocess of xecuting a C program 9

    8ord Pro!essor7editor9 /sed to Sour!e (i$etype in program (ormat9 textand corrections

    Compi$er ttempts to

    translate programinto machine

    code

    /nsuccessful

    rror

  • 8/13/2019 Unit -1(Problem solving and program desing in c UNIT -1

    19/27

    1"( Computer .oftware

    machine language program that is ready to run" 8or your sample program, the linkermight 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 beginexecution with the first instruction" s the program executes, it takes input datafrom one or more sources and sends results to output andBor secondary storagedevices"

    .ome computer systems require the user to ask the ?. to carry out separatelyeach step illustrated in 8ig" 1"11 " Aowever, most high0level language compilers aresold as part of an integrated development environment 7&* 9, a package thatcombines a simple word processor with a compiler, linker, and loader" .uch environ0ments give the developer menus from which to select the next step, and if the devel0oper tries a step that is out of sequence, the environment simply fills in the missingsteps automatically"

    E;e!uting a ProgramTo execute a machine language program, the C#/ must examine each programinstruction in memory and send out the command signals required to carry out theinstruction" lthough the instructions normally are executed in sequence, as we willdiscuss later, it is possible to have the C#/ skip over some instructions or executesome instructions more than once"

    *uring execution, data can be entered into memory and manipulated in somespecified way" .pecial program instructions are used for entering or scanning aprogram s data 7called input data9 into memory" fter the input data have beenprocessed, instructions for displaying or printing values in memory can be executed to

    display the program results" The lines displayed by a program are called theprogram output "

    >et s use the situation described in 8ig" 1"1= Gexecuting a water bill programstored in memoryGas an example" The first step of the program scans into memorydata that describe the amount of water used" &n step =, the program manipulatesthe data and stores the results of the computations in memory" &n the final step, thecomputational results are displayed as a water bill"

  • 8/13/2019 Unit -1(Problem solving and program desing in c UNIT -1

    20/27

    .* Chapter 1 ?verview of Computers and #rogramming

    (I)URE "#"*

    8low of &nformation *uring #rogram xecution

  • 8/13/2019 Unit -1(Problem solving and program desing in c UNIT -1

    21/27

    1"3 The .oftware *evelopment $.&.

    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 ofapples purchased and the cost per pound of apples "

    2ext, summari e the information contained in the underlined phrases:

  • 8/13/2019 Unit -1(Problem solving and program desing in c UNIT -1

    22/27

    Chapter 1 ?verview of Computers and #rogramming

    #roblem &nputs

    )ua*tity o+ apples purc,ased -i* pou*dscost per pou*d o+ apples -i* dollars per pou*d

    #roblem ?utputtotal cost o+ apples i* dollars

    ?nce you know the problem inputs and outputs, develop a list of formulas thatspecify 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 ourparticular 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 theessential variables and their relationships is called abstraction "

    * .&;2

    *esigning the algorithm to solve the problem requires you to develop a list of stepscalled an algorithm to solve the problem and to then verify that the algorithmsolves the problem as intended" 5riting the algorithm is often the most difficultpart of the problem0solving process" *on t attempt to solve every detail of theproblem at the beginning! instead, discipline yourself to use top0down design" &ntop0down design 7also called divide and conquer 9, you first list the ma%or steps, orsubproblems, that need to be solved" Then you solve the original problem by solvingeach of its subproblems"

  • 8/13/2019 Unit -1(Problem solving and program desing in c UNIT -1

    23/27

    1"3 The .oftware *evelopment

  • 8/13/2019 Unit -1(Problem solving and program desing in c UNIT -1

    24/27

    "#0 App$-ing t%e Software 4eve$opment ,et%odThroughout this book, we use the first five steps of the software developmentmethod to solve programming problems" These example problems, presented asCase .tudies, begin with a problem statement" s part of the problem analysis, weidentify the data requirements for the problem, indicating the problem inputs and thedesired outputs" 2ext, we design and refine the initial algorithm" 8inally, weimplement the algorithm as a C program" 5e also provide a sample run of the programand discuss how to test the program"

    5e walk you through a sample case study next" This example includes a runningcommentary on the process, which you can use as a model in solving other problems"

    CASE STU4< Converting ,i$es to =i$ometers#F?-> ;?F&TA