You are on page 1of 57

ProgramLogicFormulation

ProgrammingLanguages
ProgrammingLanguage astandardizedcommunicationtechniquefor expressinginstructionstoacomputer Likehumanlanguages,eachlanguagehasitsown syntaxandgrammar Therearedifferenttypesofprogramminglanguages thatcanbeusedtocreateprograms,butregardlessof whatlanguageyouuse,theseinstructionsaretranslated intomachinelanguagethatcanbeunderstoodby computers.

Jedi:Introductiontoprogramming

CategoriesofProgramming Languages
High-level Programming Languages a programming language that is more user-friendly, to some extent platformindependent, and abstract from low-level computer processor operations such as memory accesses

A programming statement may be translated into one or several machine instructions by a compiler. Examples: Java, C, C++, Basic, Fortran

Jedi:Introductiontoprogramming

CategoriesofProgramming Languages
LowlevelAssemblyLanguage Assemblylanguagesaresimilartomachine languages,buttheyaremucheasiertoprogram becausetheyallowaprogrammertosubstitute namesfornumbers AssemblylanguagesareavailableforeachCPU family,andeachassemblyinstructionis translatedintoonemachineinstructionbyan assemblerprogram

Jedi:Introductiontoprogramming

ProgramDevelopmentLife Cycle
Basicstepsintryingtosolveaproblem onthecomputer: 1.ProblemDefinition 2.ProblemAnalysis 3.Algorithmdesignandrepresentation (Pseudocodeorflowchart) 4.Codinganddebugging

Jedi:Introductiontoprogramming

1.ProblemDefinition
Aclearlydefinedproblemisalreadyhalf thesolution. Computerprogrammingrequiresusto definetheproblemfirstbeforeweeventry tocreateasolution. Letusnowdefineourexampleproblem:
Createaprogramthatwilldeterminethenumberof timesanameoccursinalist.

Jedi:Introductiontoprogramming

2.ProblemAnalysis
After the problem has been adequately defined, the simplest and yet the most efficient and effective approach to solve the problem must be formulated. Usually, this step involves breaking up the problem into smaller and simpler sub problems. Example Problem: Determine the number of times a name occurs in a list Input to the program: list of names (let's call this nameList) name to look for (let's call this keyName) Output of the program: the number of times the name occurs in a list

Jedi:Introductiontoprogramming

Algorithm a clear and unambiguous specification of the steps needed to solve a problem. It may be expressed in either : -Human language (English, Tagalog) -Graphical representation like a flowchart -Pseudocode - which is a cross between human language and a programming language

3.AlgorithmDesignand representation

Jedi:Introductiontoprogramming

3.AlgorithmDesign& representationHumanLang.
ExpressingoursolutionthroughHumanlanguage: 1.Getthelistofnames,let'scallthisnameList 2.Getthenametolookfor,let'scallthisthekeyname 3.Comparethekeynametoeachofthenamesin nameList 4.Ifthekeynameisthesamewithanameinthelist,add1 tothecount 5.Ifallthenameshavebeencompared,outputtheresult

Jedi:Introductiontoprogramming

3.AlgorithmDesignand representationFlowchart

Jedi:Introductiontoprogramming

FlowchartSymbols

Jedi:Introductiontoprogramming

FlowchartSymbols

Jedi:Introductiontoprogramming

FlowchartSymbols

Jedi:Introductiontoprogramming

3.AlgorithmDesignand representationPseudocode
Count NameList KeyName Count0
NameList has names Name == KeyName?

CountCount+1 CountCount nextnameinNameList DisplayCount Stop


MoreonAlgorithms
FINITETheproblemmustbesolvableina finitenumberofoperations UNAMBIGUOUSEachinstructionmust haveauniqueinterpretation. ORDEREDEachinstructionmusthavea predecessor(exceptthestart) DEFINEDINPUT/OUTPUT

pshscs2.tripod.com/files/plf.pdf

4.CodingandDebugging
Afterconstructingthealgorithm,itisnow possibletocreatethesourcecode.Using thealgorithmasbasis,thesourcecode cannowbewrittenusingthechosen programminglanguage. Debugging Theprocessoffixingsomeerrors(bugs) inyourprogram

Jedi:Introductiontoprogramming

ProblemSolving&Solution DesignConcepts
Problemsolvingsteps(specifically algorithmdefinition)issimilarinall programminglanguages.

pshscs2.tripod.com/files/plf.pdf

SixStepsinProblemSolving
1. 2. 3. 4. 5. 6.

Identifytheproblem. Understandtheproblem. Identifyalternativewaystosolvethe problem. Selectthebestwaystosolvethe problemfromthealternatives. Listinstructionsthatenableyoutosolve theproblemfromtheselectedmethod. Evaluatethesolution.

pshscs2.tripod.com/files/plf.pdf

SevenBasicElementsof Programming

Data:Constants,Variables Input:readingofvaluesfrominputdevices (keyboard,diskdrives,etc) Output:writingofinformationtoanyoutput device(diskdrives,printer,etc) Operations:comparingvalues,assigning values,combiningvalues. Conditions/Selections:IfThenElse,Switch Case, Loops/Iterations:While,doWhile,fordo, repeatuntil Subroutines/Modules:functions,procedures

pshscs2.tripod.com/files/plf.pdf

Problemsthatcanbesolvedon computers:
Computational Problemsinvolvingsomesortof mathematicalprocessing Logical Involverelationalorlogicalprocessing Repetitive Involverepeatingasetofmathematical and/orlogicalinstruction.

pshscs2.tripod.com/files/plf.pdf

LogicalControlStructures
Elementarybuildingblocksofstructured programs Statementsthatcontroltheorderinwhich otherprogramstatementsareexecuted Refertodifferentwaysinwhichprogram instructionsmaybeexecuted

pshscs2.tripod.com/files/plf.pdf

LogicalControlStructures
1.Sequence 2.Selection/Decision 3.Iteration/Loop 4.Case

pshscs2.tripod.com/files/plf.pdf

SEQUENCE
Instructionsareexecutedintheorderinwhich theyappear Stepbystepexecutionofinstructions

pshscs2.tripod.com/files/plf.pdf

SELECTION/DECISION
Alogicalcontrolstructurethatexecute instructionsdependingontheexistenceofa condition SometimescalledanIfThenElselogical controlstructure

pshscs2.tripod.com/files/plf.pdf

ITERATION/LOOP
Alogicalcontrolstructureindicatingtherepeated executionofaseriesofsteps(orinstructions).

pshscs2.tripod.com/files/plf.pdf

CASE
Alogicalcontrolstructurethatisusedwhen therearenumerouspathstobefollowed dependingonthecontentofagivenvariable.

pshscs2.tripod.com/files/plf.pdf

Example:ProgramDevelopment Flow

pshscs2.tripod.com/files/plf.pdf

DATA
Constant Avaluethatneverchangesduringthe processingofalltheinstructionsina solution. Variable Thevalueofavariabledoeschange duringprocessing. Alsocalledasidentifier

pshscs2.tripod.com/files/plf.pdf

CONSTANT
Canbeanytypeofdata:numerical, alphanumeric(orcharacter),orspecialsymbol Two(2)kindsofconstants Literal:referstotheactualvalueitself(e.g. 3.1416,pshs) Named:usesanameoraliastorepresentan actualorliteralvalue(e.g.PI,school_name)

pshscs2.tripod.com/files/plf.pdf

VARIABLE
Canbecategorizedbythekindofdatait canhold. Theymustholddatathatareofthesame type,otherwiseamismatcherrorwill occur. Canbeanytypeofdata:numerical, alphanumeric(orcharacter),logical,or specialsymbol

pshscs2.tripod.com/files/plf.pdf

Example:Constants&variables onthecomputer
Constants 8935084,1.5,3.1416,pshs,* Variables AGE=12,PRICE=99.99,CITY=Quezon City,Student_Name=PisaydelaCruz, ZIP_CODE=1008,MARK=A, End_of_File=False

pshscs2.tripod.com/files/plf.pdf

DATATYPES
Numeric Character Logical Date/Time

pshscs2.tripod.com/files/plf.pdf

NumericalData
Includealltypesofnumbers(i.e.,integers,non integers) Theonlydatatypethatcanbeusedin calculations Subtypes: Integer:negativenumbers&wholenumbers Real:decimalnumbers Float:numbersinexponential/scientificform

pshscs2.tripod.com/files/plf.pdf

CharacterData
Consistsofallnumbers,letters,and specialcharactersavailabletothe computer(#,&,*,+,,09,AZ,az)and placedwithinquotationmarks. Cannotbeusedforcalculationsevenif theyconsistofonlynumbers. String:meansastringofcharacters Concatenation:meansjoiningoftwoor morepiecesofcharacterorstringdata

pshscs2.tripod.com/files/plf.pdf

LogicalData
Consistoftwopiecesofdatainthedata set thewordsTRUEandFALSE. Logicaldataareusedinmakingayesor nodecision.

pshscs2.tripod.com/files/plf.pdf

OPERATORS
Arethedataconnectorswithin expressionsandequations. Theytellthecomputerhowtoprocessthe data. Theyalsotellthecomputerwhattypeof processingneedstobedone (i.e.,mathematical,relational,orlogical).

pshscs2.tripod.com/files/plf.pdf

Typesofoperatorsusedin calculations&problemsolving:
1.Mathematical 2.Relational 3.Logical

pshscs2.tripod.com/files/plf.pdf

MathematicalOperators
Includethefollowing: Addition+ Subtraction Multiplication* Division/ IntegerDivision\ ModuloDivisionMOD Powers^or** FunctionsFunctionName(parameters)

pshscs2.tripod.com/files/plf.pdf

RelationalOperators
Includethefollowing: Equalto= Lessthan< Greaterthan> Lessthanorequalto<= Greaterthanorequalto>= Notequalto<>or!=

pshscs2.tripod.com/files/plf.pdf

RelationalOperators
Aprogrammerusesrelationaloperators toprogramdecisions. Theresultantofarelationaloperatoris thelogicaldatatypeTRUEorFALSE. Arealsousedtocontrolrepetitive instructionscalledloops.

pshscs2.tripod.com/files/plf.pdf

LogicalOperators
Areusedtoconnectrelational expressions(decisionmaking expressions)&toperformoperationson logicaldata. Logicaloperatorsincludethefollowing: NOTNot ANDAnd OROr

pshscs2.tripod.com/files/plf.pdf

Expressions&Equations
AnExpressionprocessesdata(theoperands)through theuseofoperators. Anequationstorestheresultantofanexpressionina memorylocationinthecomputerthroughtheequalsign( =). Equationsareoftencalledassignmentstatements. Theequalsigndoesnotmeanequality,butmeans replacedbyorisassignedthevalueof. Therighthandsideoftheequationisprocessedbefore theassignmentismade.

pshscs2.tripod.com/files/plf.pdf

Expressions&Equations

pshscs2.tripod.com/files/plf.pdf

PseudoCodeDescription Format
Format Explanation Thisisthewhere procedures,variables, types,etc.,aredeclared Format {comment} Conditional expression Process 1 Process 2 Explanation Usedforcomments. Indicatesselective processing. Iftheconditional expressionistrue, Process1is executed;ifthe conditionalexpression isfalse,Process2is executed. Indicatesaloopwith thetermination conditionattop. Theprocessis executedaslongas theconditional expressionistrue. Declaration section

Declaresthenames, types,etc.,ofprocedures ,variables. Thisistheareawhere processingisdescribed.

Processing section

Conditional expression Process

VariableExpressio
n

Assignsthevalueofthe expressiontothe variable.

Example12Branch
Whenmathematicsscoreislessthan60,thestudentgets afailingmark

MathematicsExam.
Yes SCORE 60

Declarati IntegerVariable: on SCORE section SCORE MathematicsMark Processin g section

Fail

No

Score 60
Fail DoNothing

Example23Branch
Whenmathematicsscoreislessthan60,andEnglish scoreislessthan60,thestudentgetsafailingmark.
MathematicsExam.
Yes Yes
Declarati IntegerVariable:Math.SCORE, Eng.SCORE on section Math.SCORE MathematicsMark Eng.SCORE EnglishMark Processin g section

EnglishExam.

Math.SCORE 60 Eng.SCORE 60

No

Math.Score 60 Eng.Score 60
Fail DoNothing DoNothing

Fail

No

Example33Branch
Whenmathematicsscoreislessthan60,orEnglish scoreislessthan60,thestudentgetsafailingmark.
Mathematics&EnglishExam.
Yes
Math.SCORE 60
Declarati IntegerVariable:Math.SCORE, Eng.SCORE on section Math.SCORE MathematicsMark Eng.SCORE EnglishMark Processin g section

No

Fail

Yes

Eng.SCORE 60

Math.Score 60
Fail

No

Fail

Eng.Score 60
Fail DoNothing DoNothing

Example43Branch
Whenmathematicsscoreisgreaterthanequal80 evaluationA,whenscoreislessthan80andgreaterthan equal60evaluationB,whenscoreislessthan60then evaluationC.
MathematicsExam.
80Score
Math.SCORE

Score 60

Declarati IntegerVariable:Math.SCORE on section Math.SCORE MathematicsMark Processin g section

60Score 80

Math.Score80
EvaluationA

EvaluationA EvaluationB EvaluationC

Math.Score60
EvaluationB EvaluationC

Example5Repeat
Variablexhasaninitialvalue0.Andadd1tox.Itrepeats additionwhilexisnot5(untilxbecomes5).
X0
Declarati IntegerVariable:X on section

X5
Yes

No

X 0 Processin g section

X5
X=X+1

XX+1

Example6Loop
Variablexhasaninitialvalue0.Andadd3tox.Itrepeats addition5times.
X0,Y0
Declarati IntegerVariable:X,Y on section

Y 5
Yes

No

X 0 Y 0 Processin g section

Y 5
X=X+3 Y=Y+1

XX+3 YY+1

YbecomestheLoopCounter.

Example7Loop
Calculatethesumofoddnumber1,3,5,7,and9.
X0,Y1
Loop tillY>9
Declarati IntegerVariable:X,Y on section X 0 Y 1 Processin g section

XX+Y YY+2
Loop

Y9
X=X+Y Y=Y+2

Example8LoopArray
Therearefourmoneysavingsboxes.Theirnamesare "week1","week2","week3",and"week4". Getthetotalamountofmoneyattheendofthemonth.
Save(1)120,Save(2)340 Save(3)230,Save(4)180 Sum0,i1 i4
Yes No
IntegerVariable:Sum,i Declarati on IntegerArray:Save(4) section

180 Sum 0,i1


Processin g section

Save(1) 120~Save(4)

i4
Sum=Sum+Save(i) i=i+1

SumSum+Save(i) ii+1

Example9LoopArray&Branch
Therearefourmoneysavingsboxes.Theirnameare Calculatethesumofoddnumber1,3,5,7,and9. "week1toweek4".Onlywhentheamountofsavingsonthe weekendis200ormoreisitaddedtoSum.
Save(1)120,Save(2)340 Save(3)230,Save(4)180 Sum0,i1 i4
Yes No No
IntegerVariable:Sum,i Declarati on IntegerArray:Save(4) section

180 Sum 0,i1


Processin g section

Save(1) 120~Save(4)

i4 Save(i)200
Sum=Sum+Save(i) Nothing i=i+1

Save(i)200
Yes

SumSum+Save(i) ii+1

Practice1 Sumofinteger1to10
Sum0,i1
Declarati IntegerVariable:Sum,i on section Sum 0 i 1 Processin g section

i10
Yes

No

i10
Sum=Sum+i i=i+1

SumSum+i ii+1

Practice2 GivenanarrayT(n)which containssomevaluesstoredin ascendingorder,lookfora givenvalueinthisarrayby usingthebinarysearch method.


Before
T(1) T(2) T(3)

Practice2
low mid high
T(n1 ) T(n )

Aftercomparedata& T(mid)
T(1) T(2) T(3)

mid=(low+high) 2(ignoredecimalfractions.)

T(mi d)

T(n1 )

T(n )

low high low high data< T(mid) Targetfound data> T(mid)

data= T(mid)

Practice2
Loop
low highoridx0 mid(high+Low)/2 Declarati on section

idx0,low1,highn

IntegerVariable:

idx,low,high,mid

idx 0 low 1 high n

Yes

No

data T(mid)
Yes

Processin g section

data=T(mid)

No

lowhighand idx=0 mid (low+high)/2 data=T(mid) idxmid data>T(mid)


lowmid+1 highmid1

idxmid

lowmid+1 highmid 1

Loop

You might also like