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: [Link] [Link] [Link] (Pseudocodeorflowchart) [Link]
Jedi:Introductiontoprogramming
[Link]
Aclearlydefinedproblemisalreadyhalf thesolution. Computerprogrammingrequiresusto definetheproblemfirstbeforeweeventry tocreateasolution. Letusnowdefineourexampleproblem:
Createaprogramthatwilldeterminethenumberof timesanameoccursinalist.
Jedi:Introductiontoprogramming
[Link]
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
[Link] representation
Jedi:Introductiontoprogramming
[Link]& representationHumanLang.
ExpressingoursolutionthroughHumanlanguage: [Link],let'scallthisnameList [Link],let'scallthisthekeyname [Link] nameList [Link],add1 tothecount [Link],outputtheresult
Jedi:Introductiontoprogramming
[Link] representationFlowchart
Jedi:Introductiontoprogramming
FlowchartSymbols
Jedi:Introductiontoprogramming
FlowchartSymbols
Jedi:Introductiontoprogramming
FlowchartSymbols
Jedi:Introductiontoprogramming
[Link] 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
[Link]/files/[Link]
[Link]
Afterconstructingthealgorithm,itisnow [Link] thealgorithmasbasis,thesourcecode cannowbewrittenusingthechosen programminglanguage. Debugging Theprocessoffixingsomeerrors(bugs) inyourprogram
Jedi:Introductiontoprogramming
ProblemSolving&Solution DesignConcepts
Problemsolvingsteps(specifically algorithmdefinition)issimilarinall programminglanguages.
[Link]/files/[Link]
SixStepsinProblemSolving
1. 2. 3. 4. 5. 6.
Identifytheproblem. Understandtheproblem. Identifyalternativewaystosolvethe problem. Selectthebestwaystosolvethe problemfromthealternatives. Listinstructionsthatenableyoutosolve theproblemfromtheselectedmethod. Evaluatethesolution.
[Link]/files/[Link]
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
[Link]/files/[Link]
Problemsthatcanbesolvedon computers:
Computational Problemsinvolvingsomesortof mathematicalprocessing Logical Involverelationalorlogicalprocessing Repetitive Involverepeatingasetofmathematical and/orlogicalinstruction.
[Link]/files/[Link]
LogicalControlStructures
Elementarybuildingblocksofstructured programs Statementsthatcontroltheorderinwhich otherprogramstatementsareexecuted Refertodifferentwaysinwhichprogram instructionsmaybeexecuted
[Link]/files/[Link]
LogicalControlStructures
[Link] [Link]/Decision [Link]/Loop [Link]
[Link]/files/[Link]
SEQUENCE
Instructionsareexecutedintheorderinwhich theyappear Stepbystepexecutionofinstructions
[Link]/files/[Link]
SELECTION/DECISION
Alogicalcontrolstructurethatexecute instructionsdependingontheexistenceofa condition SometimescalledanIfThenElselogical controlstructure
[Link]/files/[Link]
ITERATION/LOOP
Alogicalcontrolstructureindicatingtherepeated executionofaseriesofsteps(orinstructions).
[Link]/files/[Link]
CASE
Alogicalcontrolstructurethatisusedwhen therearenumerouspathstobefollowed dependingonthecontentofagivenvariable.
[Link]/files/[Link]
Example:ProgramDevelopment Flow
[Link]/files/[Link]
DATA
Constant Avaluethatneverchangesduringthe processingofalltheinstructionsina solution. Variable Thevalueofavariabledoeschange duringprocessing. Alsocalledasidentifier
[Link]/files/[Link]
CONSTANT
Canbeanytypeofdata:numerical, alphanumeric(orcharacter),orspecialsymbol Two(2)kindsofconstants Literal:referstotheactualvalueitself(e.g. 3.1416,pshs) Named:usesanameoraliastorepresentan actualorliteralvalue([Link],school_name)
[Link]/files/[Link]
VARIABLE
Canbecategorizedbythekindofdatait canhold. Theymustholddatathatareofthesame type,otherwiseamismatcherrorwill occur. Canbeanytypeofdata:numerical, alphanumeric(orcharacter),logical,or specialsymbol
[Link]/files/[Link]
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
[Link]/files/[Link]
DATATYPES
Numeric Character Logical Date/Time
[Link]/files/[Link]
NumericalData
Includealltypesofnumbers(i.e.,integers,non integers) Theonlydatatypethatcanbeusedin calculations Subtypes: Integer:negativenumbers&wholenumbers Real:decimalnumbers Float:numbersinexponential/scientificform
[Link]/files/[Link]
CharacterData
Consistsofallnumbers,letters,and specialcharactersavailabletothe computer(#,&,*,+,,09,AZ,az)and placedwithinquotationmarks. Cannotbeusedforcalculationsevenif theyconsistofonlynumbers. String:meansastringofcharacters Concatenation:meansjoiningoftwoor morepiecesofcharacterorstringdata
[Link]/files/[Link]
LogicalData
Consistoftwopiecesofdatainthedata set thewordsTRUEandFALSE. Logicaldataareusedinmakingayesor nodecision.
[Link]/files/[Link]
OPERATORS
Arethedataconnectorswithin expressionsandequations. Theytellthecomputerhowtoprocessthe data. Theyalsotellthecomputerwhattypeof processingneedstobedone (i.e.,mathematical,relational,orlogical).
[Link]/files/[Link]
Typesofoperatorsusedin calculations&problemsolving:
[Link] [Link] [Link]
[Link]/files/[Link]
MathematicalOperators
Includethefollowing: Addition+ Subtraction Multiplication* Division/ IntegerDivision\ ModuloDivisionMOD Powers^or** FunctionsFunctionName(parameters)
[Link]/files/[Link]
RelationalOperators
Includethefollowing: Equalto= Lessthan< Greaterthan> Lessthanorequalto<= Greaterthanorequalto>= Notequalto<>or!=
[Link]/files/[Link]
RelationalOperators
Aprogrammerusesrelationaloperators toprogramdecisions. Theresultantofarelationaloperatoris thelogicaldatatypeTRUEorFALSE. Arealsousedtocontrolrepetitive instructionscalledloops.
[Link]/files/[Link]
LogicalOperators
Areusedtoconnectrelational expressions(decisionmaking expressions)&toperformoperationson logicaldata. Logicaloperatorsincludethefollowing: NOTNot ANDAnd OROr
[Link]/files/[Link]
Expressions&Equations
AnExpressionprocessesdata(theoperands)through theuseofoperators. Anequationstorestheresultantofanexpressionina memorylocationinthecomputerthroughtheequalsign( =). Equationsareoftencalledassignmentstatements. Theequalsigndoesnotmeanequality,butmeans replacedbyorisassignedthevalueof. Therighthandsideoftheequationisprocessedbefore theassignmentismade.
[Link]/files/[Link]
Expressions&Equations
[Link]/files/[Link]
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:[Link], [Link] on section [Link] MathematicsMark [Link] EnglishMark Processin g section
EnglishExam.
[Link] 60 [Link] 60
No
[Link] 60 [Link] 60
Fail DoNothing DoNothing
Fail
No
Example33Branch
Whenmathematicsscoreislessthan60,orEnglish scoreislessthan60,thestudentgetsafailingmark.
Mathematics&EnglishExam.
Yes
[Link] 60
Declarati IntegerVariable:[Link], [Link] on section [Link] MathematicsMark [Link] EnglishMark Processin g section
No
Fail
Yes
[Link] 60
[Link] 60
Fail
No
Fail
[Link] 60
Fail DoNothing DoNothing
Example43Branch
Whenmathematicsscoreisgreaterthanequal80 evaluationA,whenscoreislessthan80andgreaterthan equal60evaluationB,whenscoreislessthan60then evaluationC.
MathematicsExam.
80Score
[Link]
Score 60
Declarati IntegerVariable:[Link] on section [Link] MathematicsMark Processin g section
60Score 80
Math.Score80
EvaluationA
EvaluationA EvaluationB EvaluationC
Math.Score60
EvaluationB EvaluationC
Example5Repeat
[Link] additionwhilexisnot5(untilxbecomes5).
X0
Declarati IntegerVariable:X on section
X5
Yes
No
X 0 Processin g section
X5
X=X+1
XX+1
Example6Loop
[Link] 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
[Link] "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
[Link] 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