Program Logic Formulation

57
 Program Logic Formulation Program Logic Formulation

Transcript of Program Logic Formulation

   

Program Logic FormulationProgram Logic Formulation

   

Programming LanguagesProgramming Languages ● ● Programming LanguageProgramming Language– – a standardized communication technique for a standardized communication technique for expressing instructions to a computerexpressing instructions to a computer

– – Like human languages, each language has its own Like human languages, each language has its own syntax and grammarsyntax and grammar

– – There are different types of programming languages There are different types of programming languages that can be used to create programs, but regardless of that can be used to create programs, but regardless of what language you use, these instructions are translated what language you use, these instructions are translated into machine language that can be understood by into machine language that can be understood by computers.computers.

Jedi: Introduction to programming

   

Categories of ProgrammingCategories of ProgrammingLanguagesLanguages

● ● High-level Programming LanguagesHigh-level Programming Languages– – a programming language that is more a programming language that is more

user-friendly, to some extent platform-user-friendly, to some extent platform-independent, and abstract from low-level independent, and abstract from low-level computer processor operations such as computer processor operations such as memory accessesmemory accesses

– – A programming statement may be A programming statement may be translated into one or several machine translated into one or several machine instructions by a instructions by a compilercompiler..

Examples: Java, C, C++, Basic, FortranExamples: Java, C, C++, Basic, Fortran

Jedi: Introduction to programming

   

Categories of ProgrammingCategories of ProgrammingLanguagesLanguages

 ● ● Low­level Assembly LanguageLow­level Assembly Language– – Assembly languages are similar to machine Assembly languages are similar to machine 

languages, but they are much easier to program languages, but they are much easier to program because they allow a programmer to substitute because they allow a programmer to substitute names for numbersnames for numbers

– – Assembly languages are available for each CPU Assembly languages are available for each CPU family, and each assembly instruction is family, and each assembly instruction is translated into one machine instruction by an translated into one machine instruction by an assembler programassembler program

Jedi: Introduction to programming

   

Program Development LifeProgram Development LifeCycleCycle

 ● ● Basic steps in trying to solve a problem Basic steps in trying to solve a problem on the computer:on the computer:

1. Problem Definition1. Problem Definition2. Problem Analysis2. Problem Analysis3. Algorithm design and representation3. Algorithm design and representation(Pseudocode or flowchart)(Pseudocode or flowchart)4. Coding and debugging4. Coding and debugging

Jedi: Introduction to programming

   

1. Problem Definition1. Problem Definition

 ● ● A clearly defined problem is already half A clearly defined problem is already half the solution.the solution. ● ● Computer programming requires us to Computer programming requires us to define the problem first before we even try define the problem first before we even try to create a solution.to create a solution. ● ● Let us now define our example problem:Let us now define our example problem:

““Create a program that will determine the number of Create a program that will determine the number of times a name occurs in a list.”times a name occurs in a list.”

Jedi: Introduction to programming

   

2. Problem Analysis2. Problem Analysis● ● After the problem has been adequately defined, theAfter the problem has been adequately defined, thesimplest and yet the most efficient and effective approach tosimplest and yet the most efficient and effective approach tosolve the problem must be formulated.solve the problem must be formulated.

● ● Usually, this step involves breaking up the problem intoUsually, this step involves breaking up the problem intosmaller and simpler sub problems.smaller and simpler sub problems.

● ● Example Problem:Example Problem:Determine the number of times a name occurs in a listDetermine the number of times a name occurs in a list

● ● Input to the program:Input to the program:list of names (let's call this nameList)list of names (let's call this nameList)name to look for (let's call this keyName)name to look for (let's call this keyName)

● ● Output of the program:Output of the program: the number of times the name occurs in a listthe number of times the name occurs in a list

Jedi: Introduction to programming

   

3. Algorithm Design and3. Algorithm Design andrepresentationrepresentation

● ● AlgorithmAlgorithma clear and unambiguous a clear and unambiguous specification of the steps needed to specification of the steps needed to solve a problem.solve a problem.

● ● It may be expressed in either :It may be expressed in either :--Human language (English, Tagalog)Human language (English, Tagalog)-Graphical representation like a -Graphical representation like a flowchartflowchart-Pseudocode - which is a cross -Pseudocode - which is a cross between human language and a between human language and a programming languageprogramming language Jedi: Introduction to programming

   

3. Algorithm Design &3. Algorithm Design &representation–Human Lang.representation–Human Lang.

 ● ● Expressing our solution through Expressing our solution through Human languageHuman language::

1. Get the list of names, let's call this 1. Get the list of names, let's call this nameListnameList2. Get the name to look for, let's call this the 2. Get the name to look for, let's call this the keynamekeyname3. Compare the 3. Compare the keyname keyname to each of the names in to each of the names in 

nameListnameList4. If the 4. If the keyname keyname is the same with a name in the list, add 1 is the same with a name in the list, add 1 

to the to the countcount5. If all the names have been compared, output the result5. If all the names have been compared, output the result

Jedi: Introduction to programming

   

3. Algorithm Design and3. Algorithm Design andrepresentation ­ Flowchartrepresentation ­ Flowchart

Jedi: Introduction to programming

   

Flowchart SymbolsFlowchart Symbols

Jedi: Introduction to programming

   

Flowchart SymbolsFlowchart Symbols

Jedi: Introduction to programming

   

Flowchart SymbolsFlowchart Symbols

Jedi: Introduction to programming

   

3. Algorithm Design and3. Algorithm Design andrepresentation ­ Pseudocoderepresentation ­ Pseudocode

○Count○NameList○KeyName●Count   0←

●next name in NameList

● Display Count● Stop

NameList has names

● Count ← Count + 1

Name == KeyName?

● Count ← Count

   

More on AlgorithmsMore on Algorithms

FINITE –FINITE –  The problem must be solvable in a The problem must be solvable in a finite number of operationsfinite number of operations  

UNAMBIGUOUS – UNAMBIGUOUS – Each instruction must Each instruction must have a unique interpretation. have a unique interpretation. 

ORDERED – ORDERED – Each instruction must have a Each instruction must have a predecessor (except the start)predecessor (except the start)

DEFINED INPUT/OUTPUT ­ DEFINED INPUT/OUTPUT ­ 

pshscs2.tripod.com/files/plf.pdf

   

4. Coding and Debugging4. Coding and Debugging

 ● ● After constructing the algorithm, it is now After constructing the algorithm, it is now possible to create the source code. Using possible to create the source code. Using the algorithm as basis, the source code the algorithm as basis, the source code can now be written using the chosen can now be written using the chosen programming language.programming language.

 ● ● DebuggingDebugging– – The process of fixing some errors (bugs) The process of fixing some errors (bugs) 

in your programin your program

Jedi: Introduction to programming

   

Problem Solving & Solution Problem Solving & Solution Design ConceptsDesign Concepts

• Problem solving steps (specifically Problem solving steps (specifically algorithm definition) is similar in all algorithm definition) is similar in all programming languages.programming languages.

pshscs2.tripod.com/files/plf.pdf

   

Six Steps in Problem SolvingSix Steps in Problem Solving

1.1. Identify the problem.Identify the problem.2.2. Understand the problem.Understand the problem.3.3. Identify alternative ways to solve the Identify alternative ways to solve the 

problem.problem.4.4. Select the best ways to solve the Select the best ways to solve the 

problem from the alternatives.problem from the alternatives.5.5. List instructions that enable you to solve List instructions that enable you to solve 

the problem from the selected method.the problem from the selected method.6.6. Evaluate the solution.Evaluate the solution.

pshscs2.tripod.com/files/plf.pdf

   

Seven Basic Elements of Seven Basic Elements of ProgrammingProgramming

• DataData: : Constants, VariablesConstants, Variables• InputInput: : reading of values from input devices reading of values from input devices 

(keyboard, disk drives, etc…)(keyboard, disk drives, etc…)• OutputOutput: : writing of information to any output writing of information to any output 

device (disk drives, printer, etc…)device (disk drives, printer, etc…)• OperationsOperations: : comparing values, assigning comparing values, assigning 

values, combining values.values, combining values.• Conditions / SelectionsConditions / Selections: : If­Then­Else, Switch­If­Then­Else, Switch­

Case, Case, • Loops / IterationsLoops / Iterations: : While, do­While, for­do, While, do­While, for­do, 

repeat­untilrepeat­until• Subroutines / ModulesSubroutines / Modules: : functions, proceduresfunctions, procedures

pshscs2.tripod.com/files/plf.pdf

   

Problems that can be solved on Problems that can be solved on computers:computers:

ComputationalComputationalProblems involving some sort of Problems involving some sort of mathematical processingmathematical processing

LogicalLogicalInvolve relational or logical processingInvolve relational or logical processing

RepetitiveRepetitiveInvolve repeating a set of mathematical Involve repeating a set of mathematical and / or logical instruction.and / or logical instruction.

pshscs2.tripod.com/files/plf.pdf

   

Logical Control StructuresLogical Control Structures

• Elementary building blocks of structured Elementary building blocks of structured programsprograms

• Statements that control the order in which Statements that control the order in which other program statements are executedother program statements are executed

• Refer to different ways in which program Refer to different ways in which program instructions may be executedinstructions may be executed

pshscs2.tripod.com/files/plf.pdf

   

Logical Control StructuresLogical Control Structures

1. Sequence1. Sequence2. Selection / Decision2. Selection / Decision3. Iteration / Loop3. Iteration / Loop4. Case4. Case

pshscs2.tripod.com/files/plf.pdf

   

SEQUENCESEQUENCE

• Instructions are executed in the order in which Instructions are executed in the order in which they appearthey appear

• ““Step­by­step” execution of instructionsStep­by­step” execution of instructions

pshscs2.tripod.com/files/plf.pdf

   

SELECTION / DECISIONSELECTION / DECISION• A logical control structure that execute A logical control structure that execute 

instructions depending on the existence of a instructions depending on the existence of a conditioncondition

•   Sometimes called an “If­Then­Else” logical Sometimes called an “If­Then­Else” logical control structurecontrol structure

pshscs2.tripod.com/files/plf.pdf

   

ITERATION / LOOPITERATION / LOOP

• A logical control structure indicating the repeated A logical control structure indicating the repeated execution of a series of steps (or instructions).execution of a series of steps (or instructions).

pshscs2.tripod.com/files/plf.pdf

   

CASECASE

• A logical control structure that is used when A logical control structure that is used when there are numerous paths to be followed there are numerous paths to be followed depending on the content of a given variable.depending on the content of a given variable.

pshscs2.tripod.com/files/plf.pdf

   

Example: Program Development Example: Program Development FlowFlow

pshscs2.tripod.com/files/plf.pdf

   

DATADATA

ConstantConstant– – A value that never changes during the   A value that never changes during the   processing of all the instructions in a processing of all the instructions in a solution.solution.

VariableVariable  – – The value of a variable does change The value of a variable does change during processing.during processing. –  – Also called as “identifier”Also called as “identifier”

pshscs2.tripod.com/files/plf.pdf

   

CONSTANTCONSTANT

• Can be any type of data: numerical, Can be any type of data: numerical, alphanumeric (or character), or special symbolalphanumeric (or character), or special symbol

• Two (2) kinds of constantsTwo (2) kinds of constants        – – Literal: refers to the actual value itself (e.g.   Literal: refers to the actual value itself (e.g.   

3.1416, “pshs”)3.1416, “pshs”)    –     – Named: uses a name or alias to represent anNamed: uses a name or alias to represent an        actual or literal value (e.g. PI, school_name)actual or literal value (e.g. PI, school_name)

pshscs2.tripod.com/files/plf.pdf

   

VARIABLEVARIABLE

• Can be categorized by the kind of data it Can be categorized by the kind of data it can hold.can hold.

• They must hold data that are of the same They must hold data that are of the same type, otherwise a mismatch error will type, otherwise a mismatch error will occur.occur.

• Can be any type of data: numerical, Can be any type of data: numerical, alphanumeric (or character), logical, or alphanumeric (or character), logical, or special symbolspecial symbol

pshscs2.tripod.com/files/plf.pdf

   

Example: Constants & variablesExample: Constants & variables         on the computer         on the computer

• ConstantsConstants        8935084, ­1.5, 3.1416, “pshs”, “*”8935084, ­1.5, 3.1416, “pshs”, “*”• VariablesVariables        AGEAGE=12, =12, PRICEPRICE=99.99, =99.99, CITYCITY=“Quezon=“Quezon        City”, City”, Student_NameStudent_Name=“Pisay dela Cruz”,=“Pisay dela Cruz”,        ZIP_CODEZIP_CODE=“1008”, =“1008”, MARKMARK=“A”,=“A”,        End_of_FileEnd_of_File=False=False

pshscs2.tripod.com/files/plf.pdf

   

DATA TYPESDATA TYPES

• NumericNumeric• CharacterCharacter• LogicalLogical• Date / TimeDate / Time

pshscs2.tripod.com/files/plf.pdf

   

Numerical DataNumerical Data

• Include all types of numbers (i.e., integers, non­Include all types of numbers (i.e., integers, non­integers)integers)

• The only data type that can be used in The only data type that can be used in calculationscalculations

• Subtypes:Subtypes: –  – Integer: negative numbers & whole numbersInteger: negative numbers & whole numbers –  – Real: decimal numbersReal: decimal numbers –  – Float: numbers in exponential / scientific formFloat: numbers in exponential / scientific form

pshscs2.tripod.com/files/plf.pdf

   

Character DataCharacter Data

•   Consists of all numbers, letters, and Consists of all numbers, letters, and specialcharacters available to the specialcharacters available to the computer (#, &, *, +, ­, 0­9, A­Z, a­z) and computer (#, &, *, +, ­, 0­9, A­Z, a­z) and placed within quotation marks.placed within quotation marks.

•   Cannot be used for calculations even if Cannot be used for calculations even if they consist of only numbers.they consist of only numbers.

•   String: means a string of charactersString: means a string of characters•   Concatenation: means joining of two or Concatenation: means joining of two or 

more pieces of character or string datamore pieces of character or string data

pshscs2.tripod.com/files/plf.pdf

   

Logical DataLogical Data

•   Consist of two pieces of data in the data Consist of two pieces of data in the data setset– – the words TRUE and FALSE.the words TRUE and FALSE.

•   Logical data are used in making a yes or Logical data are used in making a yes or no decision.no decision.

pshscs2.tripod.com/files/plf.pdf

   

OPERATORSOPERATORS

•   Are the data connectors within Are the data connectors within expressions and equations.expressions and equations.

•   They tell the computer how to process the They tell the computer how to process the data.data.

•   They also tell the computer what type of They also tell the computer what type of processing needs to be done processing needs to be done 

      (i.e., mathematical, relational, or logical).(i.e., mathematical, relational, or logical).

pshscs2.tripod.com/files/plf.pdf

   

Types of operators used inTypes of operators used incalculations & problem solving:calculations & problem solving:1. Mathematical1. Mathematical2. Relational2. Relational3. Logical3. Logical

pshscs2.tripod.com/files/plf.pdf

   

Mathematical OperatorsMathematical Operators

Include the followingInclude the following::  – – Addition           +Addition           + –  – Subtraction        ­Subtraction        ­ –  – Multiplication     *Multiplication     * –  – Division           /Division           / –  – Integer Division \Integer Division \ –  – Modulo Division    MODModulo Division    MOD –  – Powers             ^ or **Powers             ^ or ** –  – Functions          FunctionName (parameters)Functions          FunctionName (parameters)

pshscs2.tripod.com/files/plf.pdf

   

Relational OperatorsRelational Operators

Include the followingInclude the following::  – – Equal to                  =Equal to                  = –  – Less than                 <Less than                 < –  – Greater than             >Greater than             > –  – Less than or equal to     <=Less than or equal to     <= –  – Greater than or equal to >=Greater than or equal to >= –  – Not equal to              < > or !=Not equal to              < > or !=

pshscs2.tripod.com/files/plf.pdf

   

Relational OperatorsRelational Operators

•   A programmer uses relational operators A programmer uses relational operators to program decisions.to program decisions.

•   The resultant of a relational operator is The resultant of a relational operator is the logical data type TRUE or FALSE.the logical data type TRUE or FALSE.

•   Are also used to control repetitive Are also used to control repetitive instructions called loops.instructions called loops.

pshscs2.tripod.com/files/plf.pdf

   

Logical OperatorsLogical Operators

•   Are used to connect relational Are used to connect relational expressions (decision­making expressions (decision­making expressions) & to perform operations on expressions) & to perform operations on logical data.logical data.

•   Logical operators include the following:Logical operators include the following:                    NOT  – NotNOT  – Not                    AND – AndAND – And                    OR  – OrOR  – Or

pshscs2.tripod.com/files/plf.pdf

   

Expressions & EquationsExpressions & Equations• An Expression processes data (the operands) through An Expression processes data (the operands) through 

the use of operators.the use of operators.• An equation stores the resultant of an expression in a An equation stores the resultant of an expression in a 

memory location in the computer through the equal sign ( memory location in the computer through the equal sign ( = ).= ).

• Equations are often called “assignment statements.”Equations are often called “assignment statements.”• The equal sign does not mean equality, but means The equal sign does not mean equality, but means 

“replaced by” or “is assigned the value of.”“replaced by” or “is assigned the value of.”• The right­hand side of the equation is processed before The right­hand side of the equation is processed before 

the assignment is made.the assignment is made.

pshscs2.tripod.com/files/plf.pdf

   

Expressions & EquationsExpressions & Equations

pshscs2.tripod.com/files/plf.pdf

   

Assigns the value of the expression to the variable. 

●Variable Expressio←n

This is the area where processing is described.

Declares the names, types, etc., of procedures , variables.

This is the where procedures, variables, types, etc., are declared

ExplanationFormat

Pseudo­Code Description Format

Declaration section

Processing section

Indicates a loop with the termination condition at top.   The process is executed as long as the conditional expression is true.

   ●  Process

Indicates selective processing.   If the conditional expression is true, Process 1 is executed; if the conditional expression is false, Process 2 is executed.

   ●  Process 1

   ●  Process 2

Used for comments.{comment}

ExplanationFormat

Conditional expression

Conditional expression

   

Example 1  “2 Branch”When mathematics score is less than 60, the student gets a failing mark

SCORE < 60

Mathematics Exam.

Fail

Yes

No

Declaration section

 ○ Integer Variable: SCORE

 ● SCORE ←   Mathematics Mark

Processing section

Score < 60 ● Fail

 ● Do Nothing

   

Example 2  “3 Branch”When mathematics score is less than 60, and English score is less than 60, the student gets a failing mark.

Math. SCORE < 60

Mathematics Exam.

Yes

No

English Exam.

Eng. SCORE < 60

Fail

Yes

No

Declaration section

 ○ Integer Variable: Math.SCORE, Eng.SCORE

 ● Math.SCORE ←   Mathematics Mark

Processing section

Math.Score < 60

 ● Fail

 ● Do Nothing

 ● Eng.SCORE ←   English Mark

Eng.Score < 60

 ● Do Nothing

   

When mathematics score is less than 60, or English score is less than 60, the student gets a failing mark.

Example 3  “3 Branch”

Math. SCORE < 60

Mathematics & English Exam.

Yes No

Fail Yes

No

Eng. SCORE < 60

Fail

Declaration section

 ○ Integer Variable: Math.SCORE, Eng.SCORE

 ● Math.SCORE ←   Mathematics Mark

Processing section

Math.Score < 60 ● Fail

 ● Do Nothing

 ● Eng.SCORE ←   English Mark

Eng.Score < 60

 ● Do Nothing

 ● Fail

   

Example 4  “3 Branch”When mathematics score is greater than equal 80 evaluation A, when score is less than 80 and greater than equal 60 evaluation B, when score is less than 60 then evaluation C.

Declaration section

 ○ Integer Variable: Math.SCORE

 ● Math.SCORE ←   Mathematics Mark

Processing section

Math.Score 80≧

 ● Evaluation A

 ● Evaluation C

Math.Score 60≧

 ● Evaluation B

Math. SCORE

Mathematics Exam.

80 Score≦ Score < 60

Evaluation A

60  Score≦ < 80

Evaluation B

Evaluation C

   

Example 5  “Repeat”Variable x has an initial value 0. And add 1 to x. It repeats addition while x is not 5 (until x becomes 5).

X ≠ 5

X   0←

No

Yes

X   X+← 1

Declaration section

 ○ Integer Variable: X

   ● X ←   0

Processing section

X ≠5

 ● X = X + 1

   

Example 6  “Loop”Variable x has an initial value 0. And add 3 to x. It repeats addition 5 times.

Y   < 5

X   0, Y   0← ←

No

Yes

X   X + ← 3

Y    Y + ← 1

Y becomes the Loop Counter.

Declaration section

 ○ Integer Variable: X, Y

   ● X ←   0

Processing section Y   < 5

 ● X = X + 3

   ● Y ←   0

 ● Y = Y + 1

   

Example 7  “Loop”Calculate the sum of odd number 1, 3, 5, 7, and 9.

Declaration section

 ○ Integer Variable: X, Y

   ● X ←   0

Processing section Y   9≦

 ● X = X + Y

   ● Y ←   1

 ● Y = Y + 2

X   0, Y   1← ←

X   X + Y ←

Y    Y + ← 2

Looptill Y > 9

Loop

   

Example 8  “Loop Array”There are four money savings boxes. Their names are "week1", "week2", "week3", and "week4". Get the total amount of money at the end of the month. 

i   4≦

Save(1)   120, Save(2)   340← ←Save(3)   230, Save(4)   180← ←

Sum   0, i   1← ←

No

Yes

Sum   Sum + Save(i) ←

i    i + ← 1

Declaration section

 ○ Integer Variable: Sum, i

   ● Save(1)←   120 ~ Save(4) ←  180

Processing section i   4≦

 ● Sum = Sum + Save(i)

   ● Sum ←   0,  i   1←

 ● i = i + 1

 ○ Integer Array: Save(4)

   

Example 9  “Loop Array & Branch”Calculate the sum of odd number 1, 3, 5, 7, and 9.There are four money savings boxes. Their name are "week1 to week4". Only when the amount of savings on the weekend is 200 or more is it added to Sum.

Declaration section

 ○ Integer Variable: Sum, i

   ● Save(1)←   120 ~ Save(4) ←  180

Processing section

i   4≦

 ● Sum = Sum + Save(i)

   ● Sum ←   0,  i   1←

 ● i = i + 1

 ○ Integer Array: Save(4)

Save(i)   200≧

 ● Nothing

i   4≦

Save(1)   120, Save(2)   340← ←Save(3)   230, Save(4)   180← ←

Sum   0, i   1← ←

No

Yes

Sum   Sum + Save(i) ←

i    i + ← 1

Save(i)   200≧No

Yes

   

Practice 1Sum of integer 1 to 10

i   10≦

Sum   0, i   1← ←

No

Yes

Sum   Sum + i ←

i    i + ← 1

Declaration section

 ○ Integer Variable: Sum, i

   ● Sum ←   0

Processing section i   10≦

 ● Sum = Sum + i

   ● i ←   1

 ● i = i + 1

   

Practice 2

Given an array T(n) which contains some values stored in ascending order, look for a given value in this array by using the binary search method.

   

Practice 2T(n

)T(n­1

)………T(3)T(2)T(1)

low ← ------ mid -------→ high

Before

T(n)

T(n­1)…

T(mid)

…T(3)T(2)T(1)

After compare data & T(mid)

low ← ---→ high low ← ----→ highdata < 

T(mid)data > T(mid)

data = T(mid)

mid =(low + high) / 2  (ignore decimal fractions.)

Target found

   

Practice 2

data = T(mid)

idx   0, low   1, high   n← ← ←

Yes

idx   mid ←

Loop

low   > high or idx ≠ 0

Loop

mid   (high + Low)/2←

data   > T(mid)Yes

low   mid + 1 ←

No

No

high   mid ←  - 1 

Declarati

on section

 ○ Integer Variable: idx, low, high, mid

   ● idx ←   0

Processin

g section

low  high and ≦idx = 0

 ● mid   ←     (low + high)/2

   ● low ←   1   ● high ←   n

data = T(mid) ● idx   mid←

 ● low   mid+1←

 ● high mid ­1←

data > T(mid)