UNIT – I PART - B
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
Pointers for Structuring a Program
⚫ Use four logic structures:
⚪ Sequential structure
⚪ Decision structure
⚪ Loop structure
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,
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.
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)
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
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.
⚫ Example Calculate the Income Tax
⚫ Input Total Income
⚫ Calculate the Tax
Coupling
⚫ There are three ways to couple modules:
⚪ Global variables
⚪ Parameters
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
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.
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
Contd..
Calc(hrs,rate,*pay) formal parameters pay=hrs*rate
Exit
Print(pay) formal parameters Print pay
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
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
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
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
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
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.
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
Flowchart for Sequential Structure
Algorithm
1. Enter Name, Age
2. Print Name, Age
3. End
Flowchart
Name Age
Enter Name, Age
Print Name, Age
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.
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
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
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
Interactivity Chart
InterestControl
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
Coupling and Data Dictionary
InterestControl
Read
Calc
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
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
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
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
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)
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
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.
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
Flowchart for Decision Structure
A
B If
<Condition(s)>
Instruction set
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
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
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
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
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
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
Using Straight through Logic
Algorithm If Age < 16 then
Charge = 7
If Age > = 16 and Age < 65 then
Charge = 10
If Age >= 65 then
Using Straight through Logic Flowchart
A
If Age < 16
If Age >16 and Age < 65
If Age >= 65
Charge = 7
Charge = 10
Charge = 5
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
Example Positive Logic
⚫ Sale Commission
⚫ <=2000 0.02
⚫ 2001-4000 0.04
⚫ 4001-6000 0.07
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
Example Negative Logic
⚫ Sale Commission
⚫ <=2000 0.02
⚫ 2001-4000 0.04
⚫ 4001-6000 0.07
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 =
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?
SUMMARY
⚫ Straight Through Logic
⚫ Negative Logic
⚫ Positive Logic
⚫ Conversion Type
Home Work examples
⚫ Draw positive and negative logic for following conditions.
⚫ bonus=10 when pay<=1000
⚫ Bonus=50 when 1000 < pay<=2000
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.
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
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
While/WhileEnd
⚫ While the condition is true, repeat all instructions between the while and whileEnd.
⚫ Algorithm:
While < Condition(s) > Instruction
Instruction …..
…..
While/WhileEnd
⚫ Flowchart:
A
While
<Condition(s)>
Instruction
Instruction
B
F
Decision equivalent to While/WhileEnd
Algorithm Flowchart
If <Condition(s) >
then
Instruction
Instruction
Go to 100
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.
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.
Repeat/Until Loop
⚫ Format of Repeat/Until algorithm is: Repeat
Instruction Instruction …..
…..
Repeat/Until Loop
⚫ Flowchart A
Instruction
Instruction
Until
<Condition(s)>
B
T F
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.
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
…..
…..
Automatic – Counter Loop
⚫ Flowchart A
C
Begin End Step
Instruction
Instruction
C
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.
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
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
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
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
Problem Solving with Case Logic Structure
⚫ Objectives:
⚪ Develop problems using the case logic structure in conjunction with the loop, decision and sequential logic structure.
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.
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
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.
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.
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.