csc118 topic 2

10
 CSC118   FUNDAMENTALS OF ALGORITHM DEVELOPMENT Chapter 2: Introduction to Problem Solving Using Computer  A. Problem Solving 1. What  is  problem?  Unsettled matter demanding solutions or decision and requiring usually considerable thought or skill for its proper solution or decision 2. What  is solution?   An action or process of  solving a problem, also;  The fact or state of  a problem being solved, also;  An answer to or means of  answering a problem.  From the definition, the problem and solution are interrelated and therefore we believe that a problem should not be investigated separately from its solution. Therefore, to solve a problem, three important steps should be performed: i. Understand the problem thoroughly ii. Understand the conditions and requirements of  the problem iii. Search for alternative solutions and select a general solution 3.  Are computers intelligence?   Computers are very powerful machines but like other machines posses no intelligence. They programmed to solve problems. 4. What  is a  program?   A program is a set of  instructions which are commands to computers to perform specific operations on data. Instructions within a program are organized in such a way, when the program is run on a computer; it results in the solution of  a problem. 5. What  is a  programmer?   People who write programs for computers are called programmers. It is the programmer’s responsibility to write a correct program since a computer only faithfully obeys the commands specified by the instructions; it does not correct them if  they are in error. If  the program is not correct, erroneous results are obtained. 

description

1 class hour, 2 laboratory hours - 7 weeks; 1 creditThe latest version of a widely used spreadsheet program will be taught. Topics will include creating and problem-solving using spreadsheets, entering data and formulas, correcting errors, the range, copy and formatting instructions, printing, tables, and graphs. Not open to students who have successfully completed CSC

Transcript of csc118 topic 2

  • CSC118FUNDAMENTALSOFALGORITHMDEVELOPMENTChapter2:IntroductiontoProblemSolvingUsingComputerA. ProblemSolving

    1. Whatisproblem?

    Unsettled matter demanding solutions or decision and requiring usually considerablethoughtorskillforitspropersolutionordecision

    2. Whatissolution?

    Anactionorprocessofsolvingaproblem,also; Thefactorstateofaproblembeingsolved,also; Ananswertoormeansofansweringaproblem.

    From the definition, the problem and solution are interrelated and thereforewe believe that aproblem should not be investigated separately from its solution. Therefore, to solve a problem,

    threeimportantstepsshouldbeperformed:

    i. Understandtheproblemthoroughly

    ii. Understandtheconditionsandrequirementsoftheproblem

    iii. Searchforalternativesolutionsandselectageneralsolution

    3. Arecomputersintelligence?

    Computersareverypowerfulmachinesbutlikeothermachinespossesnointelligence.Theyprogrammedtosolveproblems.

    4. Whatisaprogram?

    Aprogram isa setof instructionswhichare commands to computers toperform specificoperationsondata. Instructionswithinaprogramareorganized in suchaway,when the

    programisrunonacomputer;itresultsinthesolutionofaproblem.

    5. Whatisaprogrammer?

    Peoplewhowriteprogramsforcomputersarecalledprogrammers. It istheprogrammersresponsibility to write a correct program since a computer only faithfully obeys the

    commandsspecifiedbytheinstructions;itdoesnotcorrectthemiftheyareinerror.Ifthe

    programisnotcorrect,erroneousresultsareobtained.

  • CSC118FUNDAMENTALSOFALGORITHMDEVELOPMENTChapter2:IntroductiontoProblemSolvingUsingComputer

    Toproduce a correctprogram, aprogrammer goes through two (2)differentbut relatedphases:theproblemsolvingphaseandtheprogrammingphase.

    a. Problemsolvingphase:

    i. First, acquire a thorough understanding of the nature of the problem, and

    deriveitsspecificationandrequirement.

    ii. Next,determine andorganize theorderofoperation and computation to be

    performedtosolvetheproblem.

    Theoutputof theproblemsolvingphase is theproblem solution in someacceptablerepresentationalformsuchasadescription inhighlystructured

    English(pseudocode)oraflowchart.Thisistheonewhatwecalledsolution

    algorithmorforshort,analgorithm.

    b. Programmingphase(Implementationphase):

    i. Write the instructions for performing the predetermined operation and

    computationsusingsuitableprogramminglanguage.

    The result is a computer program, which is run on a computer and anyerrorsdiscoveredarecorrected.

    A correct program is thus obtained and is ready to be used wheneverrequired.

    B. WhatisAlgorithm?

    Thereisnogeneraldefinitionofalgorithmaccepted. Butwecansaythatalgorithmis:

    i. Astepbystepproblemsolvingprocedure

    ii. Asequenceofinstructionthattellhowtosolveaparticularproblem.

    iii. Asetofinstructionforsolvingaproblem,especiallyonacomputer.

    iv. Acomputablesetofstepstoachieveadesiredresult.

    However,mostagreethatalgorithmhassomethingtodowithdefininggeneralizedprocessestogetoutputfromtheinput.

  • CSC118FUNDAMENTALSOFALGORITHMDEVELOPMENTChapter2:IntroductiontoProblemSolvingUsingComputer

    Therefore,wecanconcludethat:o Algorithm a stepbystepproblem solvingprocess inwhicha solution isarrived ina

    finiteamountoftime,OR

    o Analgorithmisafinitelistofsequentialstepsspecifyingactionsthatifperformedresultinsolutionofaspecificproblem.

    C. HistoryofAlgorithm

    ThewordAlgorithmcomesfromthenameoffamousPersianmathematician,AbuJafarMohammedIbnMusaAlKhowarizmi(A.D.825).Heisknownforhisextensiveworkinalgebra.

    D. RequirementofAlgorithm

    Thealgorithmshouldbehasthefollowingrequirement:i. Finiteness

    ii. Definiteness

    iii. Effectiveness

    iv. Input

    v. Output

    1. Finiteness

    Analgorithmmusteventuallyhalt(endup)afteritsstepshavebeenperformedafinitenumberoftimes.

    Analgorithmthatisnotguaranteedtohaltcannotbeimplementedbyeitherhumansormachines.

    Example:Whathappenedifwearenonstoppourwaterinaglass?

    2. Definiteness

    Everyactionspecifiedatanystepofanalgorithmmustbepreciselydefined. Everyactioncontainedinanalgorithmmustbeclearandnotsubjecttodifferent

    interpretations.Inotherwords,eachactiondescribedmustbeunambiguous.

    Forexample:GivengrammarEE+E|E*E.WhathappenifwederivesententialformE+E*EfromproductionE?

  • CSC118FUNDAMENTALSOFALGORITHMDEVELOPMENTChapter2:IntroductiontoProblemSolvingUsingComputer

    3. Effectiveness

    Everysteporactionspecifiedinanalgorithmmustbeexecutable. Example:

    a. CanweconverttemperaturefromFahrenheittoCelsius?

    b. CanweconvertcurrencyfromUSDtoRM?

    c. Canwesort100numbersinascendingorder?

    4. Input

    Analgorithmmayreceiveinputsfromoutside. Example:Calculatetheareaofonecircle.Whatistheinput?

    5. Output

    Analgorithmmustproduceoneormoreoutput. Example:Calculatetheareaofonecircle.Whatistheoutput?

    E. AlgorithmandLogicalThinking

    Todevelopthealgorithm,theprogrammerneedstoask:1. Whatdatahastobefedintothecomputer?

    2. WhatinformationdoIwanttogetoutofthecomputer?

    3. Logic:Planningtheprocessingoftheprogram.Itcontainstheinstructionsthatcausethe

    inputdatatobeturnedintothedesiredoutputdata.

    F. SearchingAlgorithm

    Searchingalistforagivenitemisoneofthemostcommonoperationsperformedonlistorarray.

    Tosearchthelist,weneedthepiecesofinformationwhichare:1. Thelist.

    Forexample:a. Abookcontainingapagesnumbers.

    b. Arraycontainingalistofelements.

  • CSC118FUNDAMENTALSOFALGORITHMDEVELOPMENTChapter2:IntroductiontoProblemSolvingUsingComputer

    2. Thelengthoflist.

    Forexample:a. Bookhasthenumberofpagesfrom1toN.

    b. Arrayconsistoffinitenumberofelements,i.eE=[1,2,3,,N].

    3. Theitemforwhichwearesearchingfor.

    Forexample:a. Wewanttosearchpagenumber4inabook.

    b. Searchnumber3fromelementofarray,E=[1,2,3,N].

    Afterthesearchiscompleted:4. IftheitemisfoundreportSuccessandreportthelocationwheretheitemisfound.

    5. Iftheitemisnotfound,thereportfailure.

    Therefore,toaccommodate4and5,wewillwriteafunctionorprocedurethatreturnavalue. Ifthesearchitemisfoundinthelist,thefunctionorprocedurereturnsthelocationin

    thelistwherethesearchitemisfound.

    Otherwise,itreturn1,indicatingthatthesearchingisunsuccessful.

    Fromthisoutput(locationoftheitembeingsearch,and1),itisclearthatthevaluereturningfunction(procedure),hasthree(3)parameters.

    1. Thearraythatcontainingthelist,letwewriteaslist.

    2. Thelengthofthelist,letwewriteaslistLength.(notethatthelistLength

  • CSC118FUNDAMENTALSOFALGORITHMDEVELOPMENTChapter2:IntroductiontoProblemSolvingUsingComputerG. ProblemSolvingusingDifferentAlgorithm(LinearSearchAlgorithmandBinarySearchAlgorithm)

    Forinstance,wesearchspecificpageinabookusingmethod:1. Linearsearchoralsoknownsequentialsearchalgorithm.

    2. Binarysearchalgorithmoralsoknownchopalgorithm.

    Weknowthatpagenumberinabookisinsequence.Howisthealgorithmtofindtheparticularpageinabook?

    Whatinformationdoweneed? Listofpageofabook,List. Numbersofpageofabook,listLength.(listLength

  • CSC118FUNDAMENTALSOFALGORITHMDEVELOPMENTChapter2:IntroductiontoProblemSolvingUsingComputer

    Pseudocode:

    Problem:Searchpage(list[],listLength,searchItem)found=FALSElist[]={1,2,3,4,5,6,7,8,9,10}listLength=10searchItem=4loc01.Start2.DOWHILEloc

  • CSC118FUNDAMENTALSOFALGORITHMDEVELOPMENTChapter2:IntroductiontoProblemSolvingUsingComputerI. BinarySearch

    Abinarysearchusesthedivideandconquertechniquetosearchthelist.1. First,searchItemiscomparedwiththemiddleelementofthelist.

    a. IFthesearchItemislessthanthemiddleelementofthelist,werestrictthe

    searchtothelowerhalfofthelist.

    b. ELSE,wesearchtheupperhalfofthelist

    Whatinformationdoweneed?1. Listofpageofabook,List.

    2. Numbersofpageofabook,listLength.(listLength

  • CSC118FUNDAMENTALSOFALGORITHMDEVELOPMENTChapter2:IntroductiontoProblemSolvingUsingComputer

    PseudocodeProblem:Searchpage(list[],listLength,searchItem)found=FALSElist[]={1,2,3,4,5,6,7,8,9,10}listLength=10searchItem=4first=0last=listLength11.Start2.DOWHILEfirstsearchItem last=middle1 ELSE first=middle+1 ENDIFENDDO3.IFfoundisTRUE returnandreportthemiddleELSEreturn1ENDIF4.Stop

    IterationofbinarysearchIteration first last middle list[middle] Found

    1 0 9 4 5 FALSE2 0 3 1 2 FALSE3 2 3 2 3 FALSE4 3 3 3 4 TRUE

  • CSC118FUNDAMENTALSOFALGORITHMDEVELOPMENTChapter2:IntroductiontoProblemSolvingUsingComputerJ. BubbleSort

    PseudocodeBubbleSort(list[],listLength)iteration1index01.Start2.DOWHILEiteration