You are on page 1of 16

11/4/2009

CCE1110 ComputerProgramming http://cce1110.ictnode.com

UniversityofMalta Oct2009

Ing.SaviourM.Baldacchino,ICTSystemsEngineering.

Algorithms g Pseudocode Controlstructures Theif selectionstatement Theifelse selectionstatement Thewhile loop Countercontrolledloops C ll dl Sentinelcontrolledcontrolledloops Assignmentoperators Incrementanddecrementoperators
Ing.SaviourM.Baldacchino,ICTSystemsEngineering. 2

UniversityofMalta Oct2009

11/4/2009

Beforewritingaprogramtosolveaproblem,oneneedsto haveathoroughunderstandingoftheproblemanda plannedapproachtosolvingit Thesolutioninvolvesexecutingaseriesofactionsina specificorder Aprocedure forsolvingaproblemintermsof


Theactions tobeexecuted,and Theorder inwhichtheyareexecuted

Iscalledanalgorithm Specifyingtheorderinwhichstatementsaretobeexecuted inacomputerprogramiscalledprogramcontrol


Ing.SaviourM.Baldacchino,ICTSystemsEngineering. 3

UniversityofMalta Oct2009

Isanartificialandinformallanguagethathelps youdevelopalgorithms d l l ith SimilartoeverydayEnglishbutnotacomputer language Helpsyouthinkoutaprogrambefore attemptingtowritethecode Carefullyprepared,pseudocodemayeasilybe convertedtoaCprogram Consistsonlyofactionstatements(definitions arenotstatementsbutmessagestothe compiler)
Ing.SaviourM.Baldacchino,ICTSystemsEngineering. 4

UniversityofMalta Oct2009

11/4/2009

Normallyprogramisexecutedsequentially However,certainlinesmaytransfercontrolto H t i li t f t lt anotherlinethanthenextoneinsequence Thenotionofstructuredprogrammingbecame synonymouswiththeeliminationofthegoto statement Programscouldbewrittenintermsofthree controlstructures:


Sequencestructure Selectionstructure Repetitionstructure

ThesequencestructureisinherentlybuiltintoC
Ing.SaviourM.Baldacchino,ICTSystemsEngineering. 5

UniversityofMalta Oct2009

Graphicalrepresentationofanalgorithm Aredrawnusingspecialpurposesymbols Symbolsareconnectedbyflowlines and directionarrows Completealgorithmsstartandendwith ovals havingthewordsBeginandEnd Forportionsofanalgorithmsmallcircles areusedinstead Actions arerepresentedbyrectangles Decisions arerepresentedbythe diamond symbol
Ing.SaviourM.Baldacchino,ICTSystemsEngineering.

Begin

Actionsymbol

Decision symbol

Begin
6

UniversityofMalta Oct2009

11/4/2009

Chasthreetypesofselectionstructures:

Theif statement
Calledasingleselectionstatement Eitherperformsnactionifaconditionistrue Orskipstheactioniftheconditionisfalse Calledthedoubleselectionstatement Performsanactionistheconditionistrue Performsadifferentactioniftheconditionisfalse Calledthemultipleselectionstatement Performsoneofmanydifferentactionsdependingonthevalue

Theifelse statement

Theswitch statement
ofanexpression

UniversityofMalta Oct2009

Ing.SaviourM.Baldacchino,ICTSystemsEngineering.

Chasthreetypesofrepetitionstructures: yp p

Thewhile Thedowhile Thefor

UniversityofMalta Oct2009

Ing.SaviourM.Baldacchino,ICTSystemsEngineering.

11/4/2009

g Usedtochooseamongdifferentcoursesof action Example:


Ifstudentsgradeisgreaterthanorequalto60 PrintPassed

Ifconditionistrueprint Passed IfconditionistrueprintPassed Ccode:


if(grade>=60) printf(Passed\n);

UniversityofMalta Oct2009

Ing.SaviourM.Baldacchino,ICTSystemsEngineering.

Flowchart

true
grade>=60

printPassed

false

UniversityofMalta Oct2009

Ing.SaviourM.Baldacchino,ICTSystemsEngineering.

10

11/4/2009

Usedtospecifydifferentactionstobeperformed whentheconditionistrueandfalse Example:

Ifstudentsgradeisgreaterthanorequalto60 PrintPassed Else printFailed

IftheconditionistrueprintsPassedotherwiseprints Failed Failed Ccode:

if(grade>=60) printf(Passed\n); else printf(Failed\n);


UniversityofMalta Oct2009 Ing.SaviourM.Baldacchino,ICTSystemsEngineering. 11

Flowchart:

printFailed

false

grade>=60

true

printPassed

UniversityofMalta Oct2009

Ing.SaviourM.Baldacchino,ICTSystemsEngineering.

12

11/4/2009

?: Closelyrelatedtotheifelsestatement <condition>?<action1>:<action2>; Example:


printf(%s\n,grade>=60?Passed:Failed);

Theformatcontrolstringoftheprintf containstheconversionspecification%sfor t i th i ifi ti % f printingacharacterstring Examplemayberewrittenas:


grade>=60?printf(Passed\n):printf(Failed\n);
Ing.SaviourM.Baldacchino,ICTSystemsEngineering. 13

UniversityofMalta Oct2009

if(grade>=90) g printf(A\n); elseif(grade>=80) printf(B\n); elseif(grade>=70) printf(C\n); elseif(grade>=60) l if( d 6 ) printf(D\n); else printf(F\n);
UniversityofMalta Oct2009 Ing.SaviourM.Baldacchino,ICTSystemsEngineering. 14

11/4/2009

p Anactionisrepeatedwhilesomecondition remainstrue Example:


Whiletherearemoreitemsonmyshoppinglist Purchasenextitemandcrossitoffmylist

Conditionremainstrueuntilthelastitemis purchased Atwhichpointtheconditionbecomesfalse andtherepetitionstops


Ing.SaviourM.Baldacchino,ICTSystemsEngineering. 15

UniversityofMalta Oct2009

Actualexample: Consideraprogramsegmentdesignedtofind thefirstpowerof2largerthan1000


product=2; while (product<=1000) product=2*product

Productisinitializedto2 Onsuccessiveloopproducttakesthevalues: 4,8,16,32,64,128,256and1024 Loopterminateswhenproductbecomes1024


Ing.SaviourM.Baldacchino,ICTSystemsEngineering. 16

UniversityofMalta Oct2009

11/4/2009

Flowchart:

true
Product<=1000

Product=2*product

false

UniversityofMalta Oct2009

Ing.SaviourM.Baldacchino,ICTSystemsEngineering.

17

Illustrationofalgorithmdevelopment g p
Aclassof10studentstookaquiz.Thegrades (integersbetween0and100)areavailable. Determinetheclassaverage

Classaverageisthesumofthegrades dividedbythenumberofstudents Algorithmmust


acceptthegrades Performaveragecalculation Printtheresult

UniversityofMalta Oct2009

Ing.SaviourM.Baldacchino,ICTSystemsEngineering.

18

11/4/2009

Pseudocode
1. 2. 3. 4. 5. 6. 7. 8. 9. 10.

Settotalto0 Setgradecounterto1 Whilegradecounteris<=10 Inputthenextgrade Addthegradetothetotal g Addonetothestudentcounter Settheclassaveragetothetotaldividedby10 Printtheclassaverage


Ing.SaviourM.Baldacchino,ICTSystemsEngineering. 19

UniversityofMalta Oct2009

#include <stdio.h> int main( void ) oid { int counter; int grade; int total; int average; total = 0; counter = 1; while( counter <= 10 ) { printf( Enter grade: ); scanf( %d, &grade ); ( , g total = total + grade; counter = counter + 1; } average = total / 10; printf( Class average is %d\n, average ); return 0 }

UniversityofMalta Oct2009

Ing.SaviourM.Baldacchino,ICTSystemsEngineering.

20

10

11/4/2009

Generalizationoftheclassaverageproblem Noindicationisgivenofhowmanygradesareto beentered. Thiscontrolstructureisoftencalledindefinite repetition becausethenumberofrepetitionsis notknown Avalueisneededtoindicateendofdataentry Thesentinelvaluemustbechosensothatit cannotbeconfusedwithavalidinputvalue 1isanacceptablevalueforthisproblem
Ing.SaviourM.Baldacchino,ICTSystemsEngineering. 21

Developaclassaveragingprogramthatwillprocessan arbitrarynumberofgradeseachtimetheprogramisrun

UniversityofMalta Oct2009

Labexercise4 4 Deitle&Deitle Page76Fig3.8

UniversityofMalta Oct2009

Ing.SaviourM.Baldacchino,ICTSystemsEngineering.

22

11

11/4/2009

Althoughonlyintegergradesareentered,the averagingcalculationislikelytoproduceadecimal number. Typeint cannotrepresentsuchanumber Datatypefloat isrequiredtohandledecimalnumbers Variableinitialization:

int counter; int grade; int total; i tt t l float average; average=(float)total/counter;


UniversityofMalta Oct2009 Ing.SaviourM.Baldacchino,ICTSystemsEngineering. 23

Thisiscalledexplicitconversion p Thecastoperatorisaunaryoperator (it takesonlyoneoperand) Otherunaryoperatorsare:theplus(+5)and minus(7) Castoperatorsassociatefromrighttoleft Havethesameprecedenceasotherunary operators


Ing.SaviourM.Baldacchino,ICTSystemsEngineering. 24

UniversityofMalta Oct2009

12

11/4/2009

printf(%.2f\n,3.446); printf(%.1f\n,3.446); i tf(% f\ 6)


/*prints3.45*/ /*prints3.4*/ /* i t */

Thefspecifiesthatafloatingpointvaluewillbe printed The.2istheprecisionofthevaluethatwillbe displayed.Ifnotspecified,thedefaultprecision is.6(6decimalplaces) is 6(6decimalplaces) Floatingpointvaluesprintedwithprecisionare roundedtotheindicatednumberofdecimal positions


Ing.SaviourM.Baldacchino,ICTSystemsEngineering. 25

UniversityofMalta Oct2009

Notalways100%precise y p Buttheyareadequatefornumerous applications Normallydevelopthroughdivision Example:10dividedby3gives3.3333 recurring Computerallocatesonlyafixedamountof C ll l fi d f memoryspacetoholdsuchavalue Thestoredfloatingpointvaluecanonlybe anapproximation
Ing.SaviourM.Baldacchino,ICTSystemsEngineering. 26

UniversityofMalta Oct2009

13

11/4/2009

Whenonecontrolstatementisusedwithin anothercontrolstatement Awhile outerstructure Anifelse insidethewhile

UniversityofMalta Oct2009

Ing.SaviourM.Baldacchino,ICTSystemsEngineering.

27

Labexercise5 5 Deitle&Deitle Page81Fig3.10

UniversityofMalta Oct2009

Ing.SaviourM.Baldacchino,ICTSystemsEngineering.

28

14

11/4/2009

c=c+3;

canbeabbreviatedwiththeaddition b bb i d i h h ddi i assignmentoperator+=


c+=3;

Thearithmeticassignmentoperatorsare:

+= = = *= /= %=
Ing.SaviourM.Baldacchino,ICTSystemsEngineering. 29

UniversityofMalta Oct2009

Unaryincrementoperator++ Unarydecrementoperator U d t t Preincrement:++a;incrementsaby1,thenuse thenewvalueofaintheexpressioninwhichit resides Postincrement:a++;usethevalueofainthe expressioninwhichitresides,thenincrementits valueby1 Thesameappliesfora anda Whenusedinastatementbyitselfthe preincrementandpostincrementhavethesame effect
Ing.SaviourM.Baldacchino,ICTSystemsEngineering. 30

UniversityofMalta Oct2009

15

11/4/2009

g Algorithms Pseudocode Controlstructures Theif selectionstatement Theifelse selectionstatement Thewhile loop Countercontrolledloops C ll dl Sentinelcontrolledcontrolledloops Assignmentoperators Incrementanddecrementoperators
Ing.SaviourM.Baldacchino,ICTSystemsEngineering. 31

UniversityofMalta Oct2009

Discussion

UniversityofMalta Oct2009

Ing.SaviourM.Baldacchino,ICTSystemsEngineering.

32

16

You might also like