ComEng22 Syllabus Revised

145
Introduction to Programming Definition Programming - the process of writing a program, or software Programming Language - Set of instructions that can be used to construct a program - come in a variety of forms and types. Different Programming Language 1. machine language - the only programs that can actually be used to operate a computer - also referred to as executable programs or executables – consist of a sequence of instructions composed of binary numbers 2. Assembly language - language that uses symbolic notation Example : ADD 1, 2 MUL 2, 3 An assembly Translation Machine Language program Language Program (assembler) program 3. Low and High Level Language Low level - language that uses instructions that are directly tied to one type of

description

hh

Transcript of ComEng22 Syllabus Revised

Introduction to ProgrammingDefinition Programming - the process of writing a program, or softwareProgramming Language - Set of instructions that can be used toconstruct a program -come in a variety of forms and types.Different Programming Language1. machine language - the only programs that can actually be used tooperate a computer- also referred to as executable programs or executables consist of a seuence of instructions composed of binary numbers!. "ssembly language - language that uses symbolic notation#xample $ "%% 1, !&'L !, ( "n assembly )ranslation &achine Languageprogram LanguageProgram *assembler+ program(. Low and ,igh Level LanguageLow level -language that uses instructions that are directly tied to one type of computer.,igh level uses instructions that resemble written languages, such as #nglish and can be run on a variety of computer types. #xample $ -.., /asic, Pascal, 0ortranSource program and source code programs written in a computer languageTwo Ways in Translating High level language to Machine Language1nterpreted language when each statement in a high-level source program istranslated individually and executed upon translation. 1nterpreter program doing the translation-ompiled language when all of the statements in a high-level source program are translated as a complete unit before any one statement is executed. -ompiler program doing the translation Procedure and Object Orientation 1n addition to classifying programming languages as high or low level, they are also classified by orientation as either procedure or ob2ect-oriented.Procedure-oriented language - the available instructions are used tocreate self-contained units referred to asproceduresPurpose of procedure $ to accept data as input and transform the datain some manner to produce a specific result asoutput . 3b2ect oriented languages - the development of graphical screens andsupport for graphical user interface *4'1+capable of displaying multiple windows. Purpose $ 'sing an ob2ect approach a program must first define thecharacteristics of the ob2ects it will be manipulating and then beconstructed of units that pass information to each ob2ect to producethe desired results.-.. - is formally classified as an ob2ect-oriented language, contains featuresfound inboth procedural- and ob2ect-oriented languages. Programming Languages3n a fundamentallevel, allcomputer programs do the same thing, theydirect a computerto accetdata !inut",to maniulate thedata ! rocess",and to roduce reorts !outut". )his implies that all computer programminglanguagesthat support aprocedureorientationmust provideessentiallythesame capabilities for performing these operations.1nput Process3utput%ata theresults %ataDifferent Tye of Programming Languages035)5"6 - 0ormula )ranslationusually for business applications that deals with whole numbers,representing inventory uantities. these applications reuire simpler mathematical calculations than scientific applications.-3/3L - -ommon /usiness 3riented Language has a picture output formats/"S1- - /eginners "ll-purpose Symbolic 1nstruction -ode ideal for creating small, easily developed, interactive programsPascal - named after the 7th century mathematician /laise Pascal. " so rigidly structured programming language-.. - extension of - a procedure oriented language developed in 1879 at"):)/ell Laboratories by ;en )hompson, %ennis 5ichie, and/rian ;ernighan- retained the extensive set of capabilities provided by - and is itselfa true general-purpose programming language- it can be used for everything from simple, interactive programs tohighly sophisticated and complex engineering and scientific programs, within the context of a truly structured language. #oftware DevelomentSoftware %evelopment Procedure- methods used by professional software developers for understanding the problem that is being solved and for creatingan effective and appropriate software solution.)hree 3verlapping Phases $1. %evelopment and %esign!. %ocumentation(. &aintenanceSoftware #ngineering is concerned with creating, efficient, reliable, andmaintainableprogramsandsystems, andit usesthesoftware developmentprocedure to achieve this goal. maintenanceProgramLife -ycle Stagesdocumentation development and design5euest for a program Program nolonger usedThree Phases of Program DevelomentPhase I$ Develoment and Design- /egins with either a statement of a problem or a specific reuest for a program which is referred to as rogram re%uirementtes $ testing codingdesignanalysis)ime'& (naly)e the roblem- reuired to ensure that the problem is clearly defined and understood *understanding of how the inputs can beused to produce the desired output+ what the system or program must do what outputs must be produced what inputs are reuired to create the desired outputs*& Develo a solution- select the exact set of steps, called an algorithm, that you will use to solve the problem- the solution is typically obtained by a series of refinements, starting with the initial algorithm found in the analysis step until an acceptable and complete algorithm is obtained.#xample $1nventory-ontrol +irst level structure program %ata #ntry -alculation 5eport Section Sect ionSection#econd level refinement structure 1nventory-ontrol 0irst level structure program %ata #ntry -alculation5eport Section Sect ion Sectionenter change%eleteScreen Printer datadata%ata5eports 5eports ,& -ode the #olution- also referred to as writing the program and implementing the solution, consists of translating the chosen design solution into a computer program.Structures $ Seuence defines the order in which instructions are executed bythe program Selection provides the capability to ma! !>=H&emoryaddresses5ariables - symbolic names in place of actual memory addresses- a name given by the programmer that is used to refer to computer storage locations.- it used in programs because the value stored in the variable can change.5ules $1. variable name must begin with a letter or underscore!. variable name cannot be a .9+ KKVRnVCcoutKKV "bsolute value is $ V KK abs*-7.(I!+ KKVRnVCcoutKKV Log function is$ V KK log*1H.I8+ KKVRnVCcoutKKV Logarithmic $V KK log19*1H.I87+ KKVRnVCcoutKKV #xponential is $ V KK exp*-(.!+ KKendlC return 9CQ/0ercises $ Asing the maniulators and math functions1. Grite a program that calculates and returns the =th root of the number H1.9, which is (.!. 1f a !9-foot ladder on the side of a building at a H>-degree angle."t which the ladder touches the building, height can be calculated as $,eight S !9 M sin H> degrees(. Grite a program that calculates the distance between two points whose coordinatesare *7, 1!+ and *(, 8+.'se the fact that the distance between two points having coordinates *x1, y1+ and *x!, y!+ is $

distance S srt*Xx1 x!Y! . Xy1 y!Y!+. Program inut -in Object-in ob2ect- stands for console input- it is linUPension plan S >U

#/L/-TIO3 #TCA-TAC/#0low of control- refers to the order in which program?s statements areexecuted.-ombination of +our standardi)ed flow of control structures1. Seuential - statements are executed in seuence, one afteranother in the order in which they are placed in the program. !. Selection - used to select which statements are to be performednext. (. 5epetition- used to repeat a set of statements=. 1nvocation - summoning set of statements as needed#election -riteria1n the solution of many problems, different actions must be ta9Cconst int S)"5)JE"L S >Cconst int S)#PJS1]# S >Cint celsius Cfloat fahrenC cout KKO%#45##S %#45##SRnPKKO-#LS1'S 0",5#6,#1)RnPKKO--------------- -------------------RnPCcelsius S S)"5)JE"LCcoutKK setiosflags *ios $$showpoint+ KK setpresision *!+Cwhile * celsius KS &"`J-#LS1'S+Nfahren S *8.9 @ >.9+ M celsius . (!.9Ccout KK setw *=+ KK celsiusKK setw*1(+KK fahrenCcelsius S celsius . S)#PJS1]#CQreturn 9CQ /0ercises $1. Grite a -.. program that converts gallons to liters.)he program should display gallons from 19 to !9 in one-gallon increment and the corresponding liter euivalent.'se the relationship that 1 gallon contains (.7H> liters.!. Grite a -.. program that converts feet to meters.)he program should display feet from ( to (9 in three-foot increment and the corresponding meter euivalent.'se the relationship that there are (.!H feet to a meter.(. 5ewrite sample program>.( to produce a table that starts at a -elsius value of 19 and ends with a -elsius value of I9, in increment of 19 degrees.Interactive while Loos- combining interactive data entry with the repetition capabilities- used to accept and then display data.#amle Program*; $Finclude KiostreamLFinclude KiomanipLusing namespace stdCint main * +Fconst int &"`6'&S S =Cint countCfloat numCcout KK ORn)his program will as< you to enter OKK &"`6'&S KK O numbers.RnP Ccount S 1Cwhile *count KS &"`6'&S+ Ncout KK ORn#nter a number $OCcin LL numCcoutKKO)he number entered is O KKnumCcount.. Qcout KK endlCreturn 9CQ /0ercises$Cefer to e0ercises on age 9B& Ase interactive while statement& startprint amessageset counteual to 1

iscount less no than or eualstop end of program to= condition is false yes *condition is true+ print the messageenter anumber $ Loopaccept a these statements numberare executed usingcineach time the loopis traversed print valueof number add 1 to count+low of control diagram #amle rogram9&9new numbercinaccept a new number new number goes in here num the variable totaltotalnew total . total S total . sum (cceting and adding a number to a total Startset count to oneset total to Aero

is count no print total

yes accept a num stop

add num to total add 1 tocount (ccumulation flow of control#amle Program*: $Finclude KiostreamLFinclude KiomanipLusing namespace stdCint main * +Fconst int &"`6'&S S =Cint countCfloat num, totalCcout KK ORn)his program will as< you to enter OKK &"`6'&S KK O numbers.RnP Ccount S 1Ctotal S 9Cwhile *count KS &"`6'&S+ Ncout KK ORn#nter a number $OCcin LL numCtotal S total . numCcoutKKO)he total is nowO KKtotalCcount.. Qcout KK ORn)he final total is O KK total Creturn 9CQ #entinels "ll of the loops we have created thus far have been examples of fixed count loops, where a counter has been used to control the number of loop iterations by means of a while statement variable condition loops may also be constructed.Sentinels - data values used to signal either the start or end of a dataseries.- must be selected so as not to conflict with legitimate data values#xample $ processing a students grade #amle rogram*< $Finclude KiostreamLusing namespace stdC int main*+N const int ,14,45"%# S 199C float grade, totalC grade S 9C total S 9Ccout KK ORn)o stop entering grades, type in any numberP Ccout KK ORn greater than 199. RnRnPCwhile *grade KS ,14,45"%#+Ntotal S total . gradeCcout KK O#nter a grade$O Ccin LL gradeC Q cout KK ORn)he total of the grades isOKK total C return 9C Q@@ value higher than 199 is entered, the loop is exited. Sum is displayed.)wo useful statements in connection with repetition statements $1. brea< forces an immediate brea, the loop continues as long as i?s value is less than or eual to 1>, and the value of i is incremented by !+#amle rogram*@ $FincludeKiostreamLFincludeKiomanipLFincludeKcmathLusing namespace stdCint main * +Nconst int &"`-3'6) S >Cint countCcout KKP6'&/#5 S_'"5# 533)RnPCcout KKP----------- -------------------RnPCcout KK setiosflags *ios $$showpoint+C for *count S 1C count ,S &"`-3'6)C count..+ cout KK setw*=+ KK countKK setw*1>+KK srt *count+ Creturn 9CQOutut $3AM8/C #GA(C/ COOT2222222222222 2222222222222222222222 ' '&BBBBB * '&.'.*'. , '&:,*B9' . *&BBBBBB 9 *&*,;B; meters long at 9 degrees -elsius, as the temperature increases to =9 degrees in a > degree increment.!. Grite a program that displays a table of !9 temperatures converting from 0ahrenheit to -elsius.)he table should start with a 0ahrenheit to -elsius.)he table should start with a 0ahrenheit value of !9 degrees and be incremented in values of = degrees. -elsius S *>.9 @ 8.9+ M *0ahrenheit (!+ Loo Programming Techni%ue'& Interactive Inut within aLoo Sample Program(! $ this program calculates the average of &"`-3'6) user-entered numbersFinclude KiostreamLusing namespace stdCint main * +Nconst int &"`-3'6) S =Cint countCfloat num, total,averageCtotal S 9.9C@@ initialiAed to Aerofor *count S 9C count K &"`-3'6)C count..+N cout KK O#nter a number$OCcin LL numCtotal S total . numCQaverage S total @ &"`-3'6)Ccout KK O)he average of the data entered isOKK averageC return 9CQ*election within a Loo#amle Program,, $this program computes the positive and negative sums of a set of &"`6'&S user entered numbersFinclude KiostreamL using namespace stdC int main * +N const int &"`6'&S S >C int i C float usenum, postot, negtotCpostot S 9Cnegtot S 9Cfor * i S 1C i KS &"`6'&SC i..+ Ncout KK O#nter a number Xpositive or negativeY $OC cin LL usenumC

if *usenum L 9+postot S postot . usenumC else negtot S negtot . usenumCQcout KK O)he positive total is O KK postotCcout KK O)he negative total isO KK negtotCreturn 9CQ#amle rogram ,,$ /valuating +unctions of One 5ariableGe want to 'B0* 1 ,0 ? * for x between ! and IFinclude KiostreamLFinclude KiomanipLFinclude KcmathLusing namespace stdCint main * +Nint x, y C coutKKOx valueyvalueRnP KKO---------------------O C for * x S !C x KS IC ..x+ Ny S 19 M pow*x, !+ . ( M x ! CcoutKK setw *=+KK xKK setw *11+KK yCQ

return 9CQ#amle Program,.$@@any euation with one un+ Ny S 19.9 M pow*x, !.9+ . (.9 M x !.9 CcoutKK setw *7+KK xKK setw *1=+KK yCQ

return 9CQ,& Interactive Loo -ontrolEalues used to control a loop may be set using variables rather than constant values.i S >C2 S 19C< S 1Cfor *count S i C count KS 2 C count S count . C count KS 19 C count S count . 1+#amle Program,9$ Finclude KiostreamLFinclude KiomanipLusing namespace stdCint main * +Nint num, finalC cout KK O#nter the final number for the table$OCcinLL finalCcout KK O6'&/#5 S_'"5# -'/#RnPCcout KKP-------------- ------------ ---------RnC

for *num S 1C num KSfinalC num..+ cout KK setw*(+ KKnum KK setw*(+ KKnum M num KK setw*7+ KKnum M num M C return 9CQ/0ercises $1. Produce a table for y valuesy S (x> !x( . x for x between > and 19 in increments of 9.!!. Grite a program that accepts individual values of gallons, one at a time, and converts each value entered to its liter euivalent before the next value is reuested.'se a for loop in your program.(.7H> liters in one gallon.(. Grite a program that selects and displays the maximum value of five numbers that are to be entered when the program is executed. *use a for loopwith both a cin and if statement internal to the loop+3ested Loos- loops contained within another loop#xample $for *a S 1C a KS>C a..+Ncout KK ORna is now O KK a for *2 S 1C 2 KS =C 2..+cout KK O2 SO KK 2CQ first loop controlled by the value of a is the outer loop second loop controlled by 2 is the inner loop3utput $a is now 12 S 1 2 S ! 2 S ( 2 S =a is now !2 S 1 2 S ! 2 S ( 2 S =a is now (2 S 1 2 S ! 2 S ( 2 S =a is now =2 S 1 2 S ! 2 S ( 2 S =a is now >2 S 1 2 S ! 2 S ( 2 S =#amle Program,;Finclude KiostreamLusing namespace stdCint main * +Nconst int &"`" S >Cconst int &"`DS =Cint a, 2Cfor *a S 1C a KS>C a..+Ncout KK ORna is now O KK a for *2 S 1C 2 KS =C 2..+cout KK O2 SO KK 2CQreturn 9CQ#amle Program,:Finclude KiostreamLusing namespace stdCint main * +N const int 6'&45"%#S S =C const int 6'&S)'%#6)S S !9C int x , y C float grade, total, averageCfor * x S 1C x KS 6'&S)'%#6)S C x..+ N total S 9C for * y S 1 C y 6'&45"%#S KSC y..+ Ncout KK O #nter an exam grade for this student$O Ccin LL gradeCtotal S total . gradeCQaverage S total @ 6'&45"%#S Ccout KK ORn )he average for studentO KK xKK O is O KK average KK ORnRnPCQ return 9CQ/0ercises $1. 0our experiments are performed, each experiment consisting of six test results. )he results for each experiment are given below.Grite a program using a nested loop to compute and display the average of the test results for each experiments.1st experiment results $ !(.! (1 1I.8 !7 !>.= !H.I!nd experiment results $ (=.H =>.! !7.8 (I.H ((.= (8.=(rd experiment results $ 18.= 1I.H 19.! !9.H 1H.8 1(.==th experiment results $ (I.8 (8 =8.! =>.1 =!.7 >9.I!."n electrical manufacturer tests five generators by measuring their output voltages at three different times.Grite a -.. program that uses a nested loop to enter each generator?s test results then computes and displays the average voltage for each generator."ssume the following generator test results$1st generator $ 1!!.> 1!!.7 1!(.9 =th generator $ 1!!.8 1!(.H 1!I.7!nd generator $ 1!9.! 1!7.9 1!>.1 >th generator $ 1!1.> 1!=.7 1!!.I(rd generator $ 1!1.7 1!=.8 1!I.9do while Loos- referred to exit-controlled loops- continues iterations through the loop while the condition is true and exits the loop when the condition is false.- chec+C

cout KK setw*19+ KK O"ll %oneP KK endlCreturn 9CQ#amle Program,;$FincludeKiostreamLusing namespace stdCint main * +Nint price, salestax, 5")#CdoNcout KK ORn#nter a price $ OCcin LL price CcoutKKP#nter rate$RnPCcinLL5")#C if *abs*price S#6)16#L+K 9.9991+brea 1>9.9 calc* + !.> I.9 19.9total product num1num! num(parameter names used in calc * +Sample 3utput $#nter three numbers $!.> I.9 19.9)he sum of the entered numbers is $1H.>)he product of the entered numbers is $1>9#xample illustrating the usefulness of passing references to called function $swap *+- exchanges the values of two main * +?s floating-pointvariables.- useful when sorting a list of numbers)he desired exchange of main * +?s variables by swap * + can only be obtained by giving swap *+ access to main?s variables, by reference parameters.#xchanging values in two variables is accomplished using three-step exchange algorithm$1. Store the first parameter?s value in a temporary location temp num1 num!!. Store the second parameter?s value in the first variable temp num1 num!(. Store the temporary value in the second parameter temp num1 num!void swap* float: num1, float: num!+Nfloat tempCtemp S num1C @@save num1?s valuenum1 S num!C @@ store num!?s value in num1num! S temp @@ change num!?s valuereturnCQ#amle Program.@$Finclude KiostreamLusing namespace stdCvoid swap*float:, float:+C @@function receives ! referencesint main*+Nfloat firstnum S !9.> , secnum S I.!> C cout KK O)he value stored in firstnum is $O KK firstsumCcout KK O)he value stored in secnum is $O KK secnum KK ORnRnP Cswap * firstnum, secnum+C @@ call the function with referencescout KKO)he value stored in firstnum is now $O KK firstnumCcout KKO)he value stored in secnum is now $O KK secnum Creturn 9CQvoid swap * float: num1, float: num!+Nfloat tempCtemp S num1C @@save num1?s valuenum1 S num!C @@ store num!?s value in num1num! S temp @@ change num!?s valuereturnCQOutut $)he value stored in firstnum is $!9.>)he value stored in secnum is $I.!>)he value stored in firstnum is now $I.!>)he value stored in secnum is now $!9.> -autions in using 5eference arguments $1. reference arguments must be variables *that is, they cannot be used to change constants+!. a function call itself gives no indication that the called function will be using reference arguments/0ercises $1. Grite a function named time * + that has an integer parameter named seconds and three integer reference parameters named hours, min and sec.)he functionis to convert the passed number of seconds into an euivalent number of hours, minutes, and seconds.'sing the references function should directly alter the respective arguments in the calling function.!. Grite a function named change * + that has integer parameter and six integer reference parameters named hundreds, fifties, twenties, tens, fives and ones respectively.)he function is to consider the passed integer value as a dollar amount and convert the value into the fewest number of euivalent bills.'sing references the function should directly alter the respective arguments in the calling function.(rrays (s (rguments1ndividual arrays elements are passed to a called function in the same manner as individual scalar variablesC they are simply included as subscripted variables when the function call is made.#xample$findJmin*voltsX!Y, voltsXIY +C - passes the values of the elementsvoltsX!Y and voltsXIY to the functionfindJmin- the called function receives accessto the actual array, rather than a copy of the values in the array. %uplication of copies of array for each function call would be wasteful of memory storageand would frustrate the effort to return multiple element changes made by the called program.*recall that a function returns at most one direct value+.)o avoid these problems, the called function is given direct access to the original array.#xample $int numsX>YCchar IYCdouble voltsX>99Y, current X>99YCfor these arrays, the following function calls can be made $findJmax*nums+CfindJch*Y +char findJch*char inJIY +void calcJtot*int arr1X>Y, double arr!X>99Y, double arr(X>99Y +#amle Program9B$Finclude KiostreamLusing namespace stdCconst int &"`#LS S >C int findJmax*int X&"`#LSY +C @@ function prototypeint main * +Nint numsX&"`#LSY S N !, 1H, 1, !7, 1IQCcout KKO)he maximum value is OKKfindJmax*nums+ KK endlCreturn 9CQ@@ find the maximum valueint findJmax* int valsX&"`#LSY +Nint i, max S valsX9YC for * i S 1Ci K &"`#LSC i..+ if *max K valsXiY + max S valsXiYC return maxCQ"ll the findJmax* + must