SCHOOL OF COMPUTER SCIENCESCHOOL OF COMPUTER

2y ago
5 Views
1 Downloads
645.23 KB
246 Pages
Last View : 1m ago
Last Download : 3m ago
Upload by : Mia Martinelli
Transcription

60-140Introduction to Algorithms and Programming I FALL 2015INSTRUCTOR: DR. C.I. EZEIFEEverybodyknows that theWORLD’S COOLESTSTUDENTS TAKE60-140SCHOOL OF COMPUTER SCIENCE,SCIENCEUNIVERSITY OF WINDSOR60-140 Dr. C.I. Ezeife 2015Slide1

1 O1.Overviewi off ComputerCt SystemsS t Computers are classified based on their generation andtype.The architecture of different generations of computersdiffer with advancement in technology.Changes in computer equipment have gone throughfour generations namely: First Generation Computers (1945-1955): Bulky,expensive consumed a lot of energy because mainexpensive,electronic component was vacuum tube. Programming was in machine language and wiring upplugl boards.b d60-140 Dr. C.I. Ezeife 2015Slide2

OOverviewi off ComputerCt SystemsS t Second Generation Computers (1955-1965): Basicelectronic components became transistors. Programmingg in Highg level languageg g with punchedpcards.Third Generation Computers (1965-1980): Basictechnology became integrated circuit (I Cs) allowingmany transistorstiton a siliconilichip.hi Faster,F t cheaperhanddsmaller in size, e.g., IBM system 360.Fourth Generation ((1980-1990):) Personal Computerspcame to use. Technology in use is large scaleintegration(LSI). Support for network and GUI.Higher Generations: Use of VLSI technology.technology60-140 Dr. C.I. Ezeife 2015Slide3

OOverviewi off ComputerCt SystemsS tVacuum Tube, Transistor, an LSI chip60-140 Dr. C.I. Ezeife 2015Slide4

TTypesoff CComputerst Computers belong to one of these types based on theirsize, processing power, number of concurrent userssupportedppand their cost. Micro or Personal Computers - support only asingle user, very compact in size. Processing poweri increasingisii butb t stilltill limitedli it d whenh sharedh d byb manyprograms and users, e.g., IBM PC, laptops. Mini Computersp((minis)) - More pprocessinggppowercan be shared among multiple users, e.g., SUNworkstations. Generally, more expensive than microcomputers A network of minis used forcomputers.60-140 Dr. C.I. Ezeife 2015Slide5

TTypesoff CComputerstimplementing powerful virtual computing processing powerslike grid and cloud computing. Grid computing appliesresources of many computers to a single problem (EuropeanData Grid) while cloud computing is used for Internet basedcomputing (e.g.,(e g online web mail like GoogleApps) whereresources and data are stored online and shared with users. Mainframe Computers – Generally, bigger than minicomputers, and support hundreds of users at a time, e.g., IBM370.370 Super Computers - Used for high performance numbercrunching applications like processing satellite data fromp , e.g.,g , Crayy Jaguargwith about 150,000,cores (CPUs).()space, Every computer system is made up of hardware and softwarecomponents.60-140 Dr. C.I. Ezeife 2015Slide6

H dHardwareCComponentst The computer hardware consists of physical electroniccomponents for performing the following functions:FunctionComponentg-Primaryy memoryy ((RAM Data Storageand ROM).-Secondary memory(disks & CD-ROMsCD-ROMs, usb orflash memory key, tapes) Data ProcessingCentral Processing Unit (CPU) Input of DataInput devices, e.g, Keyboard,mouse, web camera OutputO t t off DataD tOutputO t t devices,d ie.g., printer,i t60-140 Dr. C.I. Ezeife 2015monitor,Slide7speakers

D t StDataStorage iin MMaini MemoryM ComputersCtrepresentt iinformationfti (programs(andd data)d t )as patterns of binary digits (bits)A bit is one of the digits 0 and 1.Thus, to represent a bit, the hardware needs a devicecapable of being in one of two states (e.g., a switch of“on”on for bit 1 and “off”off for bit 0)Data and programs are represented as a string ofbinary digitsE 9 6 inE.g.,i binarybiare representedt d as 00001001 andd00000110, then passed to an add circuit to producebinary result.60-140 Dr. C.I. Ezeife 2015Slide8

D t StDataStorage Bits of data are stored in memory and bit collections ofsize 8 make 1 byte.A memory cell is made up of 1 to 4 bytes (ie. 8 bits to 32bits) depending on the word length of the system.1 kilobyte memory has 1024 bytes (approx 103 or 210)1 Megabyte memory has approx 106 or 220 bytes.1 Gigabyte memory has approx 109 or 230 bytes.IIndividualdi id l cellsll ini a machine’shi ’ maini memory are identifiedid tifi d withithunique names called addressesThe addresses of 1MB memory are 0 through 1048575 if a memorycellll isi justj t 1 byte.b t60-140 Dr. C.I. Ezeife 2015Slide9

D t StDataStorage iin MMemory Each cell of memory can be read or written (modified)individually.RAM is volatile because information stored is lost onpower off.Thus, secondary memories are used to store data forfuture use (disks, CD-ROMs and tapes).At the user and program level, physical storageaddresses are commonly referenced using logical namesor addresses like file names for block of data on disk,and variable names for memory cells.60-140 Dr. C.I. Ezeife 2015Slide10

D t StDataStorage While numeric data are represented in binary,characters are represented using standard codes.One code is ASCII (American standard code forInformation Interchange) which uses seven bits torepresent a character.Disks are a common storageg device for storingginformation for future use. Storage space is generallymore available on disk which are cheaper per unit ofstorage space than main memory.memory60-140 Dr. C.I. Ezeife 2015Slide11

Th CentralTheC t l ProcessingPi UnitU it (CPU) CPU is the part of the computer responsible forfetching instructions and data from memory andexecutingg them.Central Processing Unit (CPU): Processes information,arithmetic and logical ( , -, *, /, % andl i l/ l tilogical/relationall operationsti(e.g.(And,A d Or,O Not)).N t))It receives instructions and data from input deviceswhich it stores in main memory.yLater, it fetches these instructions and data from mainmemory and executes them to produce output (results)60-140 Dr. C.I. Ezeife 2015Slide12

Th Input/OutputTheIt/O t t DevicesD i Input device accepts input from the user and thus hasmechanisms for converting characters into bits, e.g.,keyboardyor mouse. OutputOt t deviced i displaysdi loutputt t or resultlt off processingi totthe user, e.g., printer or monitor.60-140 Dr. C.I. Ezeife 2015Slide13

S ftSoftwareCComponentst The software system drives the physical hardwarecomponents through a sequence of instructions calledp gprograms.There are many software systems in a computer (1) Operating Systems for managing computerresources, e.g., UNIX, LINUX, MSDOS, Windows2000/XP/Vista/7, Apple Macintosh OS X. (2) Compilers for translating high level languageprograms to machine language (bits), e.g., C,PASCAL compilers.60-140 Dr. C.I. Ezeife 2015Slide14

S ftSoftwareSSystemst (3) Network Software for allowing more than onecomputer to be connected together and to shareinformation ((e.g.,g , SSH,, SFTP,, telnet,, ftp).p) (4) Productivity Tools for allowing users to performdaily business and office operations in a moreproductived ti fashionf hi calledll d productivityd ti it toolst l (e.g.,(word processors, database, slide presentation andspread sheet programs) (5) Others, e.g., utility applications like viruscheckers, games, etc.60-140 Dr. C.I. Ezeife 2015Slide15

Overview of Algorithms &PProgrammingi LanguagesL ComputerpScience as a field is involved with issuesrelated to algorithm definition, coding, refinement, analysisand discovery as well as issues related to simulation of humanintelligence.A algorithmAnl ith iis a sequence off stepstforf solvingl i a specificifiproblem given its input data and the expected outputdata.Examples of real-life algorithms are operating a laundry machine, playing a video game, baking acake60-140 Dr. C.I. Ezeife 2015Slide16

Overview of Algorithms &PProgrammingi LanguagesL Algorithms?gAlgorithms are executed by human beings orcomputers. An example software for executingalgorithmsl ith isi RAPTOR whichhi h iis availableil bl on our csservers through NoMachine connection.WhenWe executede ecuted by people,peop e, ana algorithma go tneedseeds to bepresented at their level of understanding and in alanguage they understandWh executedWhent dbby machinehi ((computer),t ) an algorithml ithalso needs to be presented at its level of understandingg g it understands.and in a language60-140 Dr. C.I. Ezeife 2015Slide17

Overview of Algorithms &PProgrammingi LanguagesL ExampleEl off an algorithm:l ith ExampleEl 1.111Find the largest common divisor of 2 positive integers.(The Euclidean algorithm) Begin Input: 2 positive integers, large and small Output:O t t theirth i largestlt common divisordi i(LCD) Procedure:– Stepp 1: Read largeg and small– Step 2: Remainder large % small– Step 3: If Remainder 060-140 Dr. C.I. Ezeife 2015Slide18

Overview of Algorithms &PProgrammingi LanguagesL– then Step 3.11: LCD small Stepp 3.12: Goto Stepp4– else Step 3.21: large small StepS33.22:22 smallll RemainderRi d Step 3.23: Go to Step 2 Stepp 4: Outputp the LCD of largeg and small Step 5: End60-140 Dr. C.I. Ezeife 2015Slide19

Overview of Algorithms &PProgrammingi LanguagesL E.g., Find the largest common divisor of 40 and 1660-140 Dr. C.I. Ezeife 2015Slide20

Algorithms & ProgrammingLanguages Focus of the course (60-140) is on how to discoverprograms for solving a task (problem solving)To do this, we may need to first define the precisesequence of steps for solving this problem representedas an algorithm in pseudocode.The computer does not understand pseudocode but aprogram written in a computer language.Thus for the computer to execute our algorithmThus,algorithm, iteventually needs to be translated into a program in acomputer language like C.60-140 Dr. C.I. Ezeife 2015Slide21

Algorithms & ProgrammingLanguages Computer languages are machine language, assemblylanguage and high level languages.High level programming languages are easier to use byhumans since they are closest to English and Math.Current programming languages fall into one of thefollowing four programming paradigms:60-140 Dr. C.I. Ezeife 2015Slide22

Algorithms & ProgrammingLanguagesLISPMLMachine FortranlangsCobol AlgolSchemeBasicAPLSimulaSmalltalkGPSS60-140 Dr. C.I. Ezeife 2015functionalCAdaPacalC procedural/imperativeAda95 objectbj tJavaorienteddeclarativeProloggSlide23

Algorithms & ProgrammingLanguages BeforeBfa program writtenitt ini a highhi h levell l languagelisiexecuted by the CPU, it needs to be translated, linkedand loaded into memory in a process called compilationandd lilinking.kiProgram preparation process is: Step 1. Type Source program in high level language(eg. C lang) using text editor (eg. pico filename.c) Step 2. Compile to get object program in machinelanguage using cc filenamefilename.cc Step 3. Link to get load module Step 4. Load into memory to execute with ./a.out60-140 Dr. C.I. Ezeife 2015Slide24

Introduction to C ProgrammingLanguage A C source program file must be given a name with .cextension, e.g., test.c and this file must be preparedwith a text editor like Unix/Linux vi editor,, nedit,, ppicoor PC’s notepad or Visual C editor.A C compiler is used to compile a C program. Tocompileil on Unix/Linux,U i /Liuse: cc filename.cfilProgram instructions that violate the syntax orggrammar rules of C will cause syntaxyerrors and mustbe corrected before a successful compilation isachieved.60-140 Dr. C.I. Ezeife 2015Slide25

Introduction to C ProgrammingLanguage After compilation,Aftil titheth program iis run tot obtainbt i thethdesired result. On Unix/Linux, run with the command:./a.outGeneral structure of a simple C program is:#include stdio.h int main(void){Variables declared here; /* in correct syntax*/yprogram instructions; // in correct syntaxreturn 0;}60-140 Dr. C.I. Ezeife 2015Slide26

Introductioni to C Programmingi Language #include stdio stdio.h h /* Simple C program for finding the sum of two integers */int main(void){int num1, num2, sum;printf("Type the two integers to sum:");scanf( %d %d"scanf("%d%d , &num1,&num1 &num2);sum num1 num2;printf("sum %d \n", sum);return 0;}60-140 Dr. C.I. Ezeife 2015Slide27

Introductioni to C Programmingi Language To workTk on WiWindowsdddevelopmentlt environment,it youcan download Microsoft Visual C compiler andcheck section 1.8 of book on how to use it to type,compile,il linkli k andd executet your program.Note that sections on how to use pico and nedit texteditors on Unix/Linux are 1.5.2 and 1.5.3 of bookSection on how to use SSH and SFTP is 1.6 of book.Section on Macintosh Personal computer is 1.7N t thNotethatt eachh chapterh t endsd withith possibleiblprogramming errors and has a section on exerciseswith solutions.60-140 Dr. C.I. Ezeife 2015Slide28

2 P2.ProblemblSolvingS l i StepsSt Objectives Understand what a problem is Discuss six problem solving steps (RCMACT)Types of Problems1. Problems with Algorithmic Solutions Have a clearly defined sequence of steps that wouldgive the desired solution– E.g. baking a cake, adding two numbers60-140 Dr. C.I. Ezeife 2015Slide29

P blProblemSolvingS l i StepsSt the sequence of steps or recipe for arriving at thesolution is called the algorithm2. Problems with Heuristic Solutions Solutions emerge largely from the process of trialand error based on knowledge and experience E.g., winning a tennis game or a chess game, makinga speech at a ceremonyMany problems will require a combination of the twokinds of solution60-140 Dr. C.I. Ezeife 2015Slide30

P blProblemSolvingS l i StepsSt IIn thishi course, we are mostlyl concernedd withi h algorithmicl ih iproblems. computers are good at solving such problemsHeuristic problem solving (getting computers to speak English orrecognize patterns) is the focus of Artificial IntelligenceWhat is a Problem? It has three main components of (i) input data set, (ii) desiredoutputp data set and (iii) we want to define a sequence of steps (algorithm and/orprogram) for transforming input data to desired output data.60-140 Dr. C.I. Ezeife 2015Slide31

P blProblemSolvingS l i StepsSt What is a problem’s algorithmic solution? the sequence of steps needed to reach the desiredoutput or the best output data expressed inpseudocode.What is a Program? the sequence of steps (algorithms) expressed(coded)in a computer language like C.problemblwithihinput & outputAlgorithmicAlih iSolution60-140 Dr. C.I. Ezeife 2015CodedCd d iinto aProgramSlideDesired outputthrough computer32

P blProblemSolvingS l i StepsSt Example 2.1: Management wants to see the patterns inabsenteeism across its two departments, dept1 anddept2p for one week. It is interested in knowingg the totalabsenteeism in each department in the one week itcollected data. You are required to identify the inputand output data of this problem and attempt to definean algorithm and a program.60-140 Dr. C.I. Ezeife 2015Slide33

P blProblemSolvingS l i StepsSt60-140 Dr. C.I. Ezeife 2015Slide34

Problem SolvingS i SSteps ((RCMACT)C AC ) 1. Defining1D fi i theth ProblemP blRequirementsRit (R) clearly defining the problem in words, stating the input andoutput data as well as the processing logic. It may needknowledge or familiarity with a real life environment tounderstand the needs of a problem2. Identifying Problem Components (C) From the problem definition, identify the list of probleminputs, outputs, constraints and relationships between inputand output data expressed in coherent formulas.3. Possibly break problem solution into small modules (M) This step uses top-down design approach to solve a bigproblem using structure chart. This step may be skipped forsmall problems that do not need breaking down.60-140 Dr. C.I. Ezeife 2015Slide35

StStepsiin ProblemP blSolvingS l i 4. Design the Algorithm to solve the problem (A) Best among many alternative ways for solving theproblem is chosen. Define algorithmic solution for all modules instructure chart. E.g., solution that is most cost efficient, spaceefficient or fastest.5 Implementation and Coding (C)5. Translate the algorithmic solution from step 4 to Cprogrammingpgg languageg g to obtain a pprogram.g60-140 Dr. C.I. Ezeife 2015Slide36

StStepsiin ProblemP blSolvingS l i PPrograms havehtto obeyb ththe grammar rulesl ((syntax)t ) off C anddany violation results in a syntax error (called bug). A bug needs to be corrected during debugging before theprogram is accepted by the compiler. Other types of error that might need to be corrected duringcoding for correct results to be obtained are logic and runtimeerrors. The C implementation of Example 2.1 is: (solve)6. Test or Evaluate the solution to ensure it produces desiredresults(T) A set of complete test data is used to test the correctness of theprogram by tracing the program/algorithm with hand andrunning the program.60-140 Dr. C.I. Ezeife 2015Slide37

Diffi lti With ProblemDifficultiesP blSolvingS l i Failing to outline details of the solution (algorithm andprogram) completelyFailing to define the problem correctlyFailing to generate a sufficient list of alternativesFailingg to use a logicalgsequence of steps in the solutionPoor evaluation of the solution (algorithm andprogram)AlAlwaysrememberb thath computer ddoes not see anddneeds to be given all details about what to do.60-140 Dr. C.I. Ezeife 2015Slide38

3. Types of Algorithmic and ProgramInstructions ObjectivesObjti1. Introduce programming language concepts ofvariables, constants and their data types2. Introduce types of algorithmic and programinstructions3 Discuss Read(scanf)/Print(printf) and Assignment3.instructions.Variables and ConstantsVariables and Constants are names for storagelocations (memory cells) holding data values processedby the computer60-140 Dr. C.I. Ezeife 2015Slide39

Problem Solving Concepts(V i bl and(VariablesdCConstants)t t) Programmers define data relevant to a problem asconstants or variablesVariables and constants form building blocks forequations and expressions used in problem solving.Both variables and constants have specific data types.E.g., alphabetic or numerical valueDifferences Between Variables & Constants The value of a variable may change duringprocessing of a problem in a program, but the valueof a constant cannot change60-140 Dr. C.I. Ezeife 2015Slide40

Problem Solving Concepts(V i bl and(VariablesdCConstants)t t) The fformat ffor dThdeclaringl i variablesi bl ini bothb h an algorithml i h anddaCprogram is:datatypevariablename[,variablenames]; The format for declaring constants in both an algorithm and a Cprogram is:const datatypevariablename value[,variablenames values];[,];A constant can also be defined using preprocessor directive:#defineconstantname value60-140 Dr. C.I. Ezeife 2015Slide41

Problem Solving Concepts(V i bl and(VariablesdCConstants)t t) Example 3.1 : A class of ten students took a quiz. Thegrades (integers in the range 0 to 100) for quiz areavailable to yyou. Determine the class averageg on thequiz. Identify the constants and variables you need tosolvel thisthi problembl60-140 Dr. C.I. Ezeife 2015Slide42

V i bl andVariablesdCConstantst t Show the variables and constants needed to solve theseproblems.Example 3.3: You are required to count the number of60-140 students who have completed assignment #1.The class has 250 students Example 3.4: Find the sum and product of 2 numbers. 60-140 Dr. C.I. Ezeife 2015Slide43

IIssuesconcerningi VVariables/Constantsi bl /C t t Rules for naming variables/constants differ fromlanguage to language. C allows unlimited number ofalphanumeric characters.It is good problem solving practice to use variablenames close to the meaning of its data valuesMultiple word variable names should be separated withunderscore to make them more readable, e.g., asn1 140Use variable names with less than 15 characters toavoid ambiguities.Check Table 3.1 of text for keyword names not to beused as variable names in programs.programs60-140 Dr. C.I. Ezeife 2015Slide44

D t TDataTypes Input Data are facts (values) used by the computer toprocess algorithmic solutions and programs to aproblem while outputpp data are the results ((values))produced by the computer after running the program.IInputtDDatatE.g.Q i marksQuizkComputer stepsthrough algorithmor programOutputpDataClassAAverageEquations for findingSum & Average60-140 Dr. C.I. Ezeife 2015Slide45

D t TDataTypes Data are off many diffDdifferent types:1. Integer Data Type(called int or long int in C): Integers (wholenumbers, e.g., 1577, -18). Arithmetic operations can be performedon thisthi datad t type.tExampleEl declarationsd l tiare: inti t age, score;long int bignumber;2. Real Data Type(in C are float or double): numeric value withwholeh l numberb anddddecimali l parts,t e.g., 23.75,23 75 230000 or 22.3E53E5 iinScientific notation. Arithmetic operations are performed on thisdata type. E.g.,float salary;double bigrealnumber;60-140 Dr. C.I. Ezeife 2015Slide46

D t TDataTypes 33. CharacterCht DataD t TType(called( ll d charh iin C)C): allll lletters,ttnumbers and special symbols (surrounded by singlequotation signs), e.g., ‘A’, ‘a’, ‘1’, ‘ ’. E.g.,charh grade,d llocation ‘A’;ti‘A’4. String Data Type(implemented as charvariablename[ ] in C) Combination of more than one character(surrounded by double quotation signs), e.g.,“Randy”,Randy , “85611”,85611 , “519-111-2345”.519 111 2345 . Egdeclarations:char lastname[15], address[30];60-140 Dr. C.I. Ezeife 2015Slide47

D t TDataTypes 5. Boolean or LOGICAL Data Type (implemented withint in C) TRUE or FALSE are the only data values. In C, an int variable with a value of 0 can be treatedas logical type FALSE, while a value of not equal to0 (like 1 or a number 1) is TRUE. E.g.,int flag 0; /* declares flag as FALSE */Each data type has a data set,set the set of values fromwhich any datum of that data type is specified.60-140 Dr. C.I. Ezeife 2015Slide48

Data TypesData Type Data SetI tInteger(int)(i t) All wholeh l numbers,be.g.,-231 to (231-1)Real (float/ All real numbers (wholedouble) decimal parts)Example Data1999 -671999,671999.0,258923.610.00581CharacterCa acteAll letters,ette s, numbers,u be s, anda d ‘A’, b’, K’,,b, ,(char)special symbols. 1’, 8’, ’String(char Combination of 1 chars. “Atlas”,“956”variable[ ])LogicalTRUE FALSETRUE FALSE(int with 0or !0)60-140 Dr. C.I. Ezeife 2015Slide49

OOperationstion Character/StringCht /St i DataD t 11. Character/StringCht /St i datad t can bbe comparedd anddarranged in alphabetical order (using their ASCII codes) A comparison between characters ‘A’ and ‘B’ gives‘A’ ‘B’ since 65 66 (see Appendix A of text) The character string “Money” is greater than“Make”Make because o’ 111o 111 a’ 97a 97 but is not usedfor string comparison in C. String functions andprocessing are discussed in ch. 8.2 Other character and string operations including a lot2.of built-in functions are available in C and more detailsare in sections 4.3 and 8.4 of text.60-140 Dr. C.I. Ezeife 2015Slide50

U ffor DiffUsesDifferentt DDatat TTypes 11. NumericalNi l DataD t (integer(int/long(i t(i t/lint)i t) anddreal(float/double)) used in business, government & academicapplications for values such as salary, price, scores used for numbers that will require somecomputations on them E.g., number of employees, assignment marks,salary.2 Character2.Cht DataD t ((char)h ) used for initials, grades or things needing only onecharacter. No mathematical calculation allowed.60-140 Dr. C.I. Ezeife 2015Slide51

U ffor DiffUsesDifferentt DDatat TTypes 3. String (char variablename[ ]) used for names, labels and things needing more thanone character and not needing any mathematicalcalculation e.g., student number, phone number & accountnumber.4. Boolean (int with value 0 or !0) used in making yes-or-noyes or no decisions e.g., is a student’s grade ‘A’ ?60-140 Dr. C.I. Ezeife 2015Slide52

R l forRulesf DataD t TTypes 11. DataD t ttypes are nott usuallyll mixed.i d E.g.,E characterhtdata cannot be placed in a variable memory locationdesignated as numerical. C allows use of cast operatorf ttype conversionfori whenh necessary.2. Data defining the value of a variable or a constantwill be one of four data types:ynumerical, character,string and Boolean.3. The use of any data outside the data set of the datatype results in an error.4. Only valid operations on a data type are allowed.E.g., numbers designated as string type cannot be usedin calculations.calculations60-140 Dr. C.I. Ezeife 2015Slide53

Al ith i StructureAlgorithmicSt t [Global[Glb l Input/OutputIt/O t t Variables]V i bl ][Function Prototype list : type and parameters]Mainalgorithm{Input: Variables/ Constants lists and their typesOutput: Variables lists and their typesOthers: Variables/Constants lists and their types/* Now the body of Main Driver or Control Module is defined*/Instruction 1;Instruction 2;:Instruction n;}[function definition 1] [function definition n]60-140 Dr. C.I. Ezeife 2015Slide54

CPProgram StStructuret #include stdio.h [Optional Global Variable declarations][Function Prototype list : type and parameters]int main(void){variable declarations;/* Now the body of Main Driver or Control Module is defined*/Instruction 1;Instruction 2;:Instruction n;return 0;}[function definition 1] [f[functionti ddefinitionfi iti n]]60-140 Dr. C.I. Ezeife 2015Slide55

TTypesoff AlAlgorithmicith i IInstructionst ti An algorithmicAl ith i or program iinstructiont ti can bbe one off ththe ffollowingll itypes: 1. Read (scanf in C) or Print (printf in C) instruction - Readinstruction is used to read data from the key board while aPrint instruction prints output to the monitor.E.g.,Algorithm: Read (Num1);Print (Num1);CPProgram: scanf(“%d”,f(“%d” &N&Num1);1)printf(“%d”, Num1); 2. Assignment instruction - used to copy a computed value onthe right hand side of an equation to the memory cell labeledthe left hand side of the equation. E.g., both algorithm andprogram: sum Num1 Num2;60-140 Dr. C.I. Ezeife 2015Slide56

TTypesoff AlAlgorithmicith i IInstructionst ti 33. A ffunctionti callll - usedd tto ddelegatel t some portionti offthe task to a small independent program segment.E.g., In both algorithm and program:CCompute Product(Num1,t P d t(N 1 NNum2,&product);2 & d t) 4. A Decision instruction - used to decide betweenwhich one of a number of alternative instructions toexecute. E.g., if ((large % small) 0) lcd small; 5. A Repetition instruction - used to cause asequence of instructions to be executed repetitively anumber of times or until some event occurs. E.g,while, do-while and for instructions.60-140 Dr. C.I. Ezeife 2015Slide57

Read(scanf) and Print(printf)I t tiInstructions ReadRd ((scanf)f) iinstructionst tigett inputit datad t typedtdbby ththe user ffrom ththekey board, while print (printf) instructions display the value of avariable or an expression on the screen.The general forms of these two instructions are:In an Algorithm:Read(variable1, variable2, , variablen);Print(variable1, variable2, , variablen);The format of C program scanf and printfinstructions are:scanf(“format specifiers”, &variable1, &variable2, .,&variablen);&i bl )printf(“format specifiers”, variable1, variable2, .,variablen);60-140 Dr. C.I. Ezeife 2015Slide58

Read(scanf) and Print(printf)I t tiInstructions Both scanf and printf accept a number of parameters(arguments).A parameter could be a variable name, an expressionor a string literal, but only variable name parametersare accepted by scanf.Both scanf and printf have the first parameter as astring literal for format specifiers (specifying the datatype of the variables or data in the parameters).Format specifiers for int is %d and %ld for long int,%f for float and %lf for double, %c for char and %sfor string.60-140 Dr. C.I. Ezeife 2015Slide59

Read(scanf) and Print(printf)I t tiInstructions Example 3.5: Find the sum of two numbersAlgorithm: Read (num1, num2);Print ((“TheThe sum ofof”,, num1, “and”,and , num2, “is”,is , sum);C Program:scanf(“%d %d”, &num1, &num2);printf(“The sum of %d and %d is %d”, num1, num2,sum);Note that if the variable type for scanf is string,string then,thenthe address operator, &, does not precede the variable.60-140 Dr. C.I. Ezeife 2015Slide60

O t t FormattingOutputFtti withith printfi tf Use theUh fformat specifierifi %E or %e% to displaydi l a floatingfl i pointinumber in exponential form, %o to display in octal, %x or %X todisplay in hexadecimal. E.g.,printf (“%e\n”( %e\n , pi*10); will print 3.14159e01.3 14159e01Specify the number of columns, “c”, used to print an integer valuewith specifier %cd, e.g., %3d, %4d. E.g.printf (“%3d\n”( %3d\n , 25);printf (“%4d\n”, 25);The number of columns, “c”, and number of digits, “d”, to therighti ht off decimald i l pointi t forf a floatingfl ti pointi t valuel isi specifiedifi d withith%c.df, e.g., %8.1f.printf (“%8.1f\n”, 3.14159);60-140 Dr. C.I. Ezeife 2015Slide61

O t t FormattingOutputFtti withith printfi tf An escape sequence is used for printing characters notprintable through simple inclusion in printf controlstring.g E.g.,g , ((“ pprinted as \ ,, newline pprinted as \n)) forprintf is represented by a backslash followed by aparticular escape character. See Table 3.6 for details.Oth charactersOtherhtlik % mustt belikeb typedt d ttwicei tto bebprinted with printf as in printf(“ 50%%\n”);Check tables 3.3 to 3.6 for format control stringgparameters.60-140 Dr. C.I. Ezeife 2015Slide62

A iAssignmentt InstructionsI t ti An assignmentAiiinstructioni isi usedd to readd a valuel fromfa memorycell (any variable on its right hand side) and to assign a value to amemory cell (the only variable on its left h

The software system drives the physical hardware components through a sequence of instructions called ppgrograms. There are many software systems in a computer (1) Operating Systems for managing computer resources, e.g., UNIX, LIN

Related Documents:

1. Computer Fundamentals by P.K.Sinha _ Unit I: Introduction to Computers: Introduction, Definition, .Characteristics of computer, Evolution of Computer, Block Diagram Of a computer, Generations of Computer, Classification Of Computers, Applications of Computer, Capabilities and limitations of computer. Unit II: Basic Computer Organization:

What is Computer Architecture? “Computer Architecture is the science and art of selecting and interconnecting hardware components to create computers that meet functional, performance and cost goals.” - WWW Computer Architecture Page An analogy to architecture of File Size: 1MBPage Count: 12Explore further(PDF) Lecture Notes on Computer Architecturewww.researchgate.netComputer Architecture - an overview ScienceDirect Topicswww.sciencedirect.comWhat is Computer Architecture? - Definition from Techopediawww.techopedia.com1. An Introduction to Computer Architecture - Designing .www.oreilly.comWhat is Computer Architecture? - University of Washingtoncourses.cs.washington.eduRecommended to you b

Some common terms Desktop - a computer fitted on a work desk for personal use, not easily carried Laptop - an "all-in-one" (display, keyboard), fairly light and portable Personal computer (PC) - a computer for personal use Server computer - a computer that provides services Client computer - a computer that makes use of the services of a server .

Dwight Elementary School Burr Elementary School King Street Intermediate School Western CT Academy of International Studies Magnet Broadview Middle School Rogers Park Middle School Pathways Academy Westside Middle School Academy Great Plain School Shelter Rock School (2011 & 2014) King Street Primary School Ellsworth Ave School Pembroke Stadley .

The keys that operate the computer, very much like a typewriter, with extra keys for special functions. 3. Monitor The part of a computer system that contains the computer screen, where information is displayed. Lesson 1 Handouts - Computer Basics: A Computer Internet Course for Older Adults Module 1 - Handouts: Computer Basics! !H- 3

The computers are classified in four types on the based on data processing. Micro computer Mini computer Mainframe computer Super computer Micro Computer: Micro computers are the computers with having a microprocessor chip as it central processing unit. Originated in late 1970s.

1. Produce a sketch of the parts of a computer system 2. Define the parts of a computer system 3. Discuss the purpose of each part of the computer system 4. Define the ports on a computer 5. Discuss the purpose of each port on a computer UNIT ACTIVITIES 1. Draw a computer system and label the parts 2.

the transactions are difficult to discern. This makes it difficult to determine the overall size of activity and to know what the fair price is for a particular technology. And, of course, in highly inefficient markets a good deal of potentially valuable trade in innovation does not occur. The costs are so high and the potential value so difficult to perceive that innovation often sits “on .