• No results found

Use four logic structures: Sequential structure Decision structure Loop structure Case structure

N/A
N/A
Protected

Academic year: 2020

Share "Use four logic structures: Sequential structure Decision structure Loop structure Case structure"

Copied!
103
0
0

Loading.... (view fulltext now)

Full text

(1)

UNIT – I PART - B

(2)

Introduction to Programming Structure

⚫ Objectives:

⚪ Explain the need for structural programming

⚪ Explain how to design modules and functions, in terms of cohesion and coupling

⚪ Explain the difference between local and global variables

⚪ Explain the use of parameters

(3)

Pointers for Structuring a Program

⚫ Use four logic structures:

⚪ Sequential structure

⚪ Decision structure

⚪ Loop structure

(4)
(5)
(6)
(7)

The Modules and Their Functions

⚫ Use modules

⚫ Eliminate the rewriting of identical processes by using modules.

⚫ Use techniques to improve readability, including the four logic structures, proper naming of variables,

(8)
(9)

Modules and Their Functions

⚫ Rules for designing modules:

⚪ Each module is an entity in itself.

⚪ Each module should have a single function. (eg: printing, calculating etc.)

⚪ Each module should be small enough to be easily read and modified.

⚪ The length of a module is governed by its function and the number of instructions to be executed to perform that

function.

(10)

Types of Modules

⚫ Control Module : shows the overall flow of data through the program.

⚫ Initialization Module: processes instructions that are executed only once during the program and only at the beginning.

⚫ Process Module: (Processed by once or Loop)

⚪ Calculation Modules

⚪ Print Modules

⚪ Read and Data Validation Modules

⚫ Wrapup module: process all instructions that are executed only once during the program and only at the end (closing file, Printing Totals)

(11)

Cohesion and Coupling

⚫ Most difficult task in development of a solution to a problem is to divide the solution into modules

⚫ Question arise what should be included in each module

⚫ Modules should be independent and perform single task

(12)

Cohesion and Coupling

⚫ Cohesion is the ability for a module to work independently from all other modules.

⚫ Coupling is accomplished by some type of interface between modules that enables data to be passed from one module to another with minimum interruption.

⚪ Cohesion allows programmer to write module of a larger program and test it independently.

(13)

⚫ Example Calculate the Income Tax

⚫ Input Total Income

⚫ Calculate the Tax

(14)

Coupling

⚫ There are three ways to couple modules:

⚪ Global variables

⚪ Parameters

(15)

Local and Global Parameters

⚫ Local variables are used only by the module itself.

⚪ Cohesion is achieved

⚫ Global variables are used by all the modules.

⚪ Used for coupling

(16)
(17)

Parameters

⚫ Parameters are one of the hardest & most important concepts to understand & to use in programming.

⚫ Each section of the module is developed as cohesive module, coupled together thru parameters.

⚫ Parameters are local variables that are passed or sent from one module to another.

⚫ Eg: read(a, b, c)

⚫ The calling module is the module that processes another module.

⚫ The called module is the module being processed.

⚫ The actual parameter listing is the list of parameters that follows the module name being processed in the calling module.

(18)

Example

Controlpay //calling module process read (*hours,*payrate)

process calx(hours,payrate,*pay) actual parameters process print(pay)

end

Read(*hrs,*rate) formal parameters listings Enter hrs,rate

(19)

Contd..

Calc(hrs,rate,*pay) formal parameters pay=hrs*rate

Exit

Print(pay) formal parameters Print pay

(20)

Parameters

⚫ There are two ways to send data from one module to another through the use of parameters:

⚫ Call-by-value:

⚪ No asterisk in front of variable

⚪ Separate memory location

⚫ Call-by-reference:

⚪ Asterisk symbol in front of variable

(21)

Return Values

⚫ Functions return values when used within another

instruction.

⚫ The return value is the result of the function.

⚫ The value is only sent out of the called module into

(22)

Variable Names and Data Dictionary

⚫ Data dictionary helps to keep track of the variable usage in the program.

⚫ It contains:

⚪ Items

⚪ Variable names

⚪ Data types

⚪ The module in which they are found

⚪ Pseudonyms

⚪ Module in which pseudonyms are found

(23)

Data Dictionary

Item Variable Name

Data Type

Module Scope Pseudon ym /Module Error Check Hours Worked

Hours Numeric - real

Control Pay

Local Hrs None

Hours Worked

Hrs Numeric - real

Read / Calc

Parameter Hours Hours < 0

Pay Rate PayRate Numeric – real

Control Pay

Local Rate None

Pay Rate Rate Numeric – real

Read / Calc

Parameter PayRate Pay rate < 4.00

Net Pay Pay Numeric – real

Control Pay

Local None None

Net Pay Pay Numeric - real

Calc / Print

(24)

Four Logic Structures

⚫ Logic structure control the logic of the data flow through

the module.

⚫ The instructions and the flowcharts are combinations of

four logic structures.

⚪ Sequential structure

⚪ Decision structure

⚪ Loop structure

(25)

Problem Solving with Sequential Logic Structure

⚫ Objectives:

⚪ Use of the sequential logic structure to develop a solution to a problem

⚪ Use the proper form for instructions in an algorithm and a flowchart.

(26)

Sequential Logic Structure

⚫ Simplest logical structure.

⚫ Algorithms and flowcharts are used to represent the

problems.

⚫ An algorithm begins with the start instruction,

executes all the instructions sequentially and ends

(27)

Flowchart for Sequential Structure

Algorithm

1. Enter Name, Age

2. Print Name, Age

3. End

Flowchart

Name Age

Enter Name, Age

Print Name, Age

(28)

Solution Development

⚫ The organizing tools are used in the six steps of problem solving.

⚪ Problem Analysis Chart: helps in defining and understanding the problem, develop ideas for solution and select the best solution.

⚪ Interactivity chart: breaks the solution to the problem into parts.

⚪ IPO Chart: helps define the input, the output, and the processing steps.

⚪ The coupling diagram and the data dictionary : designates the data flow between the modules. The data dictionary records the information on the items.

⚪ The algorithms define the steps of the solution.

(29)

Solution Development

Problem: Mary Smith is looking for the bank that will

give the most return on her money over the next five years. She has $2000 to put into a saving account.

⚫ The standard equation to calculate principal plus interest at the end of a period of time is:

Amount = P * ( 1 + I/M ) ^ (N * M)

Where P = Principal amount

I = Interest

N = Number of years

(30)

Problem Analysis

Given Data Required Results

Principal - $ 2,000 Interest

Number of Years - 5 Compound Interval (#/year)

Principal plus Interest at the end of the time period

Required Processing

Amount = P * (1 + I/M) ^ (N * M)

Solution Alternatives

1. Enter all data as variables *

2. Enter principal and interest as constants and the other data as variable

3. Process one bank in one run * 4. Process all banks in one run

(31)

The Interactivity Chart

⚫ The problem is broke into four modules:

⚫ The InterestControl Module

⚪ Which controls the solution

⚫ The Read Module

⚪ Which enters the data

⚫ The Calc Module

⚪ Which calculates the amount

⚫ The Print Module

(32)

Interactivity Chart

InterestControl

(33)

IPO Chart

Input Processing Module

Reference

Output

1. Beginning Principal 2. Interest Rate 3. Number of

Years

4. Number of Times

Interest is Compounded Yearly

1. Enter Data (Change interest rate to

hundreds)

2. Calculate ending

principal and interest Amount = prinicipal * ( 1 +

interest / time) ^ ( years * time)

1. Print required results

Read Calc Print 1. Ending Principal plus interest 2. All input

(34)

Coupling and Data Dictionary

InterestControl

Read

Calc

Print

(35)

Data Dictionary

Item Variable Name

Data Type

Modules Scope Pseudonym /module

Error check

Principal Principal Numeric - real

InterestControl/ Read/Calc/Print

Local

Parameter None None

Interest Interest Numeric - real

InterestControl/ Read/Calc/Print

Local

Parameter None None

Number of years Years Numeric - real InterestControl/ Read/Calc/Print Local

Parameter None None

Compound

ing Time Time

Numeric - real

InterestControl/ Read/Calc/Print

Local

Parameter None None

Amount Amount Numeric - real

InterestControl/ Read/Calc/Print

Local

(36)

Internal and External Documentation

⚫ Documentation highlights the important details about the program.

⚫ Internal Documentation is accomplished through the use of remark or comment statements.

⚫ External documentation involves writing manuals with detailed explanation of the program and how to use it.

⚫ Documentation can be done while developing

(37)

Algorithm and Flowchart for InterestControl Module

Algorithm Flowchart Annotation Test

InterestControl

1. Process Read

(*P, *I, *Y, *T)

2. Process Calc ( P, I, Y, T, *Amount)

3. Process Print (P, I, Y, T, Amount)

4. End

Enters all data from keyboard

Calculates amount

Prints data and amount

1. Start

2. Transfer to Read

3. Transfer to Calc

4. Transfer to Print

Internal Documentation External Documentation

1. Calculates principal and interest given, beginning principal, interest rate,

number of years and compounded time interval

2. Include annotations

Same as 1 in Internal Documentation

InterestControl

Read

Calc

Print

(38)

Algorithm and Flowchart for Read Module

Algorithm Flowchart Annotation Test

Read ( *P, *I, *Y, *T)

1. Enter P, I, Y, T

2. I = I / 100

3. Exit

1. Interest is Rate

2. Time is number of times interest is compounded yearly P I Y T

Internal Documentation External Documentation

1. Remark at top: Module to enter all data and to convert interest rate

1. Explain input Data

Read

Exit

Enter P, I, Y, T

I = I /100

2000

10%

5

(39)

Algorithm and Flowchart for Calc Module

Algorithm Flowchart Annotation Test

Calc(P, I, Y, T,*A)

1. A = P * (1 + I/T) ^ (Y * T)

2. End None

A = 2000 *

(1+0.1/2)^(5*2)

A = 2000 * (1 + 0.05)^10

A = 3257.78

Internal Documentation External Documentation

1. Remark at top: Module to enter all data and interest

1. Specify equation

Calc

A = P * (1 + I/T) ^ (Y * T)

(40)

Algorithm and Flowchart for Print Module

Algorithm Flowchart Annotation Test

Print ( P, I, Y, T, A)

1. Print A, I, Y, T and A

2. Exit

1. Print each variable on a

separate line with a label

Print what is required

Internal Documentation External Documentation

1. Remark at top: Module to print required output

1. Specify output

Exit Print

(41)

Problem Solving with Decisions

⚫ Objectives:

⚪ Develop problem using the decision logic structure in conjunction with the sequential logic structure.

⚪ Use the seven problem solving tools when developing a solution using the decision logic structure.

⚪ Use nested decision instructions to develop a problem solution.

⚪ Distinguish the different uses of straight through positive and negative nested decision logic structures.

⚪ Convert a positive decision logic structure to a negative decision logic structure.

⚪ Develop decision tables given a set of policies.

(42)

Decision Logic Structure

⚫ The decision logic structure uses the If/Then/Else instruction.

⚫ If the condition is true then execute a set of

instructions else execute another set of instructions

Structure:

If < Condition(s) > Then

<True Statements> Else

(43)

Flowchart for Decision Structure

A

B If

<Condition(s)>

Instruction set

(44)

Simple Decision Statement

Algorithm

If Hours > 40 then Pay = Rate *

(40+1.5*(Hours-40))

Else

Pay = Rate * Hours

Flowchart

Pay = Rate * ( 40 + 1.5 * ( Hours – 40))

A

If Hours > 40

Pay = Rate * Hours

B

(45)

Multiple If/Then/Else Instructions

⚫ There are three types of decision logic:

⚫ Straight – through logic

⚪ All of the decisions are processed sequentially one after the other.

⚪ There is no else part of the instructions

⚫ Positive logic

⚪ Allows the flow of processing to continue through the module instead of succeeding decisions, once the resultant of a decision is true.

⚫ Negative logic

(46)

Multiple If/Then/Else Instructions

Algorithm

If PayType = “Hourly” then If Hours > 40 then

Pay = Rate * (40 + 1.5 * ( Hours – 40 )) Else

Pay = Rate * Hours Else

(47)

Multiple If/Then/Else Instructions

Flowchart

A

If PayType = Hourly

If Hours > 40

Pay = Salary

Pay = Rate * Hours Pay = Rate * ( 40 + 1.5 * (Hours – 40)

B

F

F

T

(48)

Using Straight through Logic

⚫ All conditions are tested

⚫ Least efficient because all the decision must be

processed.

⚫ Used in combinations with other two logic types and

(49)

Using Straight through Logic

⚫ Problem: Find the amount to charge people of varying ages for a concert ticket. When the person is under 16, the charge is $7, when the person is 65 or over, the

charge is $5, all others are charged $10.

⚫ The conditions are the following:

Age Charges

Age < 16 7

Age >=16 & Age <65 10

(50)

Using Straight through Logic

Algorithm If Age < 16 then

Charge = 7

If Age > = 16 and Age < 65 then

Charge = 10

If Age >= 65 then

(51)

Using Straight through Logic Flowchart

A

If Age < 16

If Age >16 and Age < 65

If Age >= 65

Charge = 7

Charge = 10

Charge = 5

(52)

Positive Logic

⚫ The computer follow a set of instructions and

continue processing if the condition is true.

⚫ If the condition is not true then the computer

processes another decision.

⚫ Positive logic always uses nested If/Then/Else

(53)
(54)
(55)

Example Positive Logic

⚫ Sale Commission

⚫ <=2000 0.02

⚫ 2001-4000 0.04

⚫ 4001-6000 0.07

(56)
(57)

Negative Logic

⚫ Negative logic is the hardest to comprehend because

of negative terms.

⚫ If the decision is false the computer processes

instructions and continues processing.

⚫ When the decision is true the computer processes the

(58)
(59)
(60)

Example Negative Logic

⚫ Sale Commission

⚫ <=2000 0.02

⚫ 2001-4000 0.04

⚫ 4001-6000 0.07

(61)
(62)

Logic Conversion

⚫ To convert positive logic to negative logic or vice versa do the following:

⚪ Change all < to >=

⚪ Change all <= to >

⚪ Change all > to <=

⚪ Change all >= to <

⚪ Change all = to <>

⚪ Change all <> to =

(63)

Which Decision Logic

To analyze which type of decision logic is to

be used consider following questions:

⚪ Which type would make the solution most readable?

⚪ Which type would make the solution the easiest to maintain or change?

⚪ Which would require the fewest tests when you don’t know anything about the data?

(64)

SUMMARY

⚫ Straight Through Logic

⚫ Negative Logic

⚫ Positive Logic

⚫ Conversion Type

(65)

Home Work examples

⚫ Draw positive and negative logic for following conditions.

⚫ bonus=10 when pay<=1000

⚫ Bonus=50 when 1000 < pay<=2000

(66)

Problem Solving with Loops

⚫ Objectives:

⚪ Develop problems using the loop logic structure in conjunction with the decision and sequential logic structures.

⚪ Use of seven problem solving tools to solve a problem using the loop logic structure.

⚪ Use counters and accumulators in a problem solution.

⚪ Use nested loop instructions to develop a problem solution

⚪ Distinguish the different uses of three types of loop logic structures.

(67)

The Loop logic structure

⚫ There are three types of loop structures:

⚪ While/WhileEnd loop

Repeats instructions while a condition is true and stops repeating

when a condition is false.

⚪ Repeat/Until loop

Repeats instructions while a condition is false or until a condition

is true.

⚪ Automatic – counter loop

Variable is set as counter and the instructions are repeated till the

(68)

Tasks to be accomplished

⚫ Counting ( Incrementing and Decrementing)

⚪ Adding a constant to the value of a variable

Eg: counter = counter + 1

⚪ For decrementing add a negative value.

Eg: counter = counter + (-1)

⚫ Accumulating (summing a group of numbers)

⚪ Adding a variable to the value of another variable

Eg: sum = sum + variable

(69)

While/WhileEnd

⚫ While the condition is true, repeat all instructions between the while and whileEnd.

⚫ Algorithm:

While < Condition(s) > Instruction

Instruction …..

…..

(70)

While/WhileEnd

⚫ Flowchart:

A

While

<Condition(s)>

Instruction

Instruction

B

F

(71)

Decision equivalent to While/WhileEnd

Algorithm Flowchart

If <Condition(s) >

then

Instruction

Instruction

Go to 100

(72)
(73)
(74)

PIAT (Putting It All Together)

Problem: Create the algorithm and the flowchart

to find the average age of all the students in a

class.

Solution

⚪ Calculates the average age in the class taking the age

of all the students as input.

(75)
(76)

Repeat/Until Loop

⚫ Repeat the set of instructions between the repeat and until, until a condition is true.

⚫ Two major difference with While/WhileEnd

⚪ In While/WhileEnd the program continues the loop as long as the condition is true whereas in Repeat/Until loop the program

stops the loop process when the resultant of the condition is

true.

(77)

Repeat/Until Loop

⚫ Format of Repeat/Until algorithm is: Repeat

Instruction Instruction …..

…..

(78)

Repeat/Until Loop

⚫ Flowchart A

Instruction

Instruction

Until

<Condition(s)>

B

T F

(79)
(80)
(81)

PIAT (Putting It All Together)

Problem: Create the algorithm and the flowchart

to find the average age of all the students in a

class.

Solution

⚪ Calculates the average age in the class taking the age

of all the students as input.

(82)
(83)

Automatic – Counter Loop

⚫ A variable value is incremented or decremented each time the loop is

repeated.

⚫ Counter variable is initialized with some starting value.

⚫ The loop repeats until the counter is greater than an ending number.

⚫ Algorithm:

Loop : Counter = Begin to End step s

Instruction

Instruction

…..

…..

(84)

Automatic – Counter Loop

⚫ Flowchart A

C

Begin End Step

Instruction

Instruction

C

(85)

Rules for Automatic Counter Loop

⚫ For incremental loop:

⚪ When the computer executes the loop instruction it sets the counter equal to the beginning number.

⚪ When the computer executes the loop end, it increments the counter.

⚪ When the counter is less than or equal to the ending number, the processing continues at the instruction that follow the loop

instruction. When the counter is greater than the ending number, the processing continues at the instruction that follows the loop-end instruction.

⚫ For decremented loop:

⚪ Counter is decremented instead of incremented at the end of the loop.

(86)
(87)

PIAT (Putting It All Together)

Problem: Create the algorithm and the flowchart

to find the average age of all the students in a

class.

Solution

⚪ Calculates the average age in the class taking the age

of all the students as input.

⚪ Algorithm and flowchart using Automatic counter

(88)
(89)
(90)
(91)
(92)

Nested Loops

⚫ Loops can be nested like decisions.

⚫ Each loop is nested inside the loop just outside it.

⚫ The inner loop does not have the same types of loop

structures as the outer loop.

⚫ Example of nested loops:

⚪ Nested loop using while/WhileEnd and Repeat/Until

(93)
(94)

Indicators

⚫ Indicators are the logical variables that a programmer

sets within a program to change the processing path or to

control when the processing of a loop should end.

⚫ Eg: flags, switches or trip values.

⚫ An error indicator designates that an error has occurred

in the input or the output. (eg: true or false)

⚫ An end-of-data indicator designates that there is no more

(95)

Recursion

⚫ Recursion occurs when a module/function calls itself.

⚫ The condition that ends the loop must be within the

module.

⚫ Recursive procedures can be replaced by conventional

loop structures.

⚫ Example of Recursion

(96)

Problem Solving with Case Logic Structure

⚫ Objectives:

⚪ Develop problems using the case logic structure in conjunction with the loop, decision and sequential logic structure.

(97)

The Case Logic Structure

⚫ Case logic structure is made of several or many set of

instructions one of which will be selected by the user and

executed by the programmer.

⚫ It does not enable the program to loop back to select

another option.

(98)

The Case Logic Structure

⚫ Format of Case logic structure: Case of variable

= CONSTANT 1:

Actions for variable = CONSTANT 1

=CONSTANT 2:

Actions for variable = CONSTANT 2

….. …..

Otherwise:

Actions for variable = anything else

(99)

PIAT (Putting It All Together)

Problem 1: A company has four different medical plans. The programmer has given each plan a code corresponding to the beginning initial of the

company:

Plan 1 = F, Plan 2 = B, Plan 3 = K and Plan 4 = E. The company pays for all of plan 1. The individual has to pay for the part of the others. The Payroll

deduction for Plan 2 = 4.65, for Plan 3 = 7.85 and for Plan 4 = 5.50. Any other codes are considered in

error. Write an algorithm and draw the flowchart for a module to determine the payroll deduction.

(100)
(101)
(102)

Codes

⚫ Codes are some characters, character strings that a programmer uses to name the options, the constants

in a case structure.

⚫ The major difference between indicators and codes are:

⚪ Codes are data to be entered by the user. Indicators are internal signals to change the processing path.

(103)

PIAT (Putting It All Together)

Problem 2: Calculate the employee’s pay. The codes are as follows:

H = Hourly Pay = rate * hours

P = Piece work Pay = rate * number of pieces C = Commission Pay = commission * sales

S = Salary Pay = salary

Any other code will considered as error.

References

Related documents

Despite national recognition of the need for pregnant women to be assessed and treated by acute physicians with training in obstetric medicine during an acute medical illness, there

University of Hull in the works of Willie Yeadon only.. Details of compilation of albums U DYE/1/2-135, with dates of compilation. Contains 210 mounted photographs with

The Japanese Employment System After the Bubble Burst , supra note 6, at 8 (“[T]he literature almost unanimously considers non-standard employment workers outside of the

The results for NRT advertising from the models with DMA locational fixed effects variables are preferred since NRT is measured at the DMA level.. However, the cigarette

According to Fonseca (1998), supported by the propositions of the Public Relations Society of America, the functions that delimit the work of a Public Relations professional are

Similarly, among the various dehydrogenase systems characterized, NADH-dependent reductase has received special attention and has been shown to reduce metmyoglobin to deoxy-

The implementation of universal health care programs, particularly in Europe, has created a kind of social experiment to evaluate changes in health disparities with more equal

Risk management, stakeholder management, resource management and intregation management are extremely important knowledge areas which project teams need to give