Title: INF354 Advanced Programming
1INF354 Advanced Programming
- Study Unit 2 Programming Part 2
2Study objectives
- Students must be able to
- Understand structured and modular programming
- Understand and use programming standards
- Do functions and procedures
- Do decision processing
- Do repetition processing
3Delphi Roadmap
- Delphi components
- Programming in Delphi
- Structured Programming
- Modular programming
- Object-oriented programming
- Standards
- Program design
- Programming steps
- Good programming practice
- Fundamental concepts and techniques
- Basic concepts
- Types of Applications
- Program Syntax
- Programming
4Structured Programs
- Programs
- That have modular design
- That only use three types of logical structures
- Sequence
- Decisions
- Loops
- Goto statements are not allowed
5Delphi Roadmap
- Delphi components
- Programming in Delphi
- Structured Programming
- Modular programming
- Object-oriented programming
- Standards
- Program design
- Programming steps
- Good programming practice
- Fundamental concepts and techniques
- Basic concepts
- Types of Applications
- Program Syntax
- Programming
6Object-oriented programming (OOP)
- Sees real life entities as objects e.g.
department, salary, person, car, invoice. - Note all of the components in the IDE are also
objects, e.g. the form, buttons, edit boxes, etc. - Object-orientation (OO) emphasises re-use of
code.
7Classes and Objects
- An objects type is called its class
- Creating a new object of a specific class is
called instantiation - I.e. an object is an instance of a class. E.g.
Mr Jones is an object of class Employee
8Object
- An object consists of
- A description of its attributes called properties
(also called instance fields, member fields,
instance variables) - The operations the object can perform called
methods. Note that objects react to events.
9Object
- Exercise
- Open Delphi
- Open the Object Inspector (it will default to
Form1) - The Object Inspector contains 5 types of
information - The name of the class TForm1
- The name of the object Form1
- The objects properties
- The events that the object respond to and
corresponding methods
10Object-oriented programming
- OOP has three fundamental concepts
- Encapsulation
- Combines the data and behaviour of an object in
one package - This provides data-hiding and re-use
- The user can manipulate an objects properties
only by passing messages to the object, using the
objects methods
11Object-oriented programming
- OOP has three fundamental concepts
- Inheritence
- Supports a parent-child relationship between
objects - For instance, a Manager class is a type of
Employee class and can therefore inherit from it - Inheritance allows the Manager class to inherit
all of the Employee class properties and methods - Inheritance creates a is a relationship between
classes
12Object-oriented programming
- OOP has three fundamental concepts
- Polymorphism
- Literally the ability to appear in many forms
- Allows a program to process objects differently
depending on their class - E.g. performs addition for numbers,
concatenation for strings and union for sets
13Delphi Roadmap
- Delphi components
- Programming in Delphi
- Structured Programming
- Modular programming
- Object-oriented programming
- Standards
- Program design
- Programming steps
- Good programming practice
- Fundamental concepts and techniques
- Basic concepts
- Types of Applications
- Program Syntax
- Programming
- Programming standards
- Naming conventions
14Programming standards
- Comments
- Use comments to describe major sections of the
program - Do not describe code itself, unless it is very
complex or non-standard -
15Programming standards
- Spacing and indentation
- Leave spaces between line, where needed, to make
it more readable - Put the different parts of decision or repetition
structures on different lines and indent them
appropriately -
-
-
If A 1 then A A 1 else A 10
versus
If A 1 then A A 1 else A 10
16Programming standards
- General Programming
- Avoid mixed-mode arithmetic
- To convert from a string to a real value use Val
- To convert from a real to a string value use Str
- For integer values use StrToInt and IntToStr
- Expressions with multiple operators must use
parentheses for clarity - Avoid global parameters
-
-
-
17Delphi Roadmap
- Delphi components
- Programming in Delphi
- Structured Programming
- Modular programming
- Object-oriented programming
- Standards
- Program design
- Programming steps
- Good programming practice
- Fundamental concepts and techniques
- Basic concepts
- Types of Applications
- Program Syntax
- Programming
- Programming standards
- Naming conventions
18Naming conventions
- Hungarian notation
- Few mnemonics in front of name to show type
- Followed by a descriptive name
- Rules for mnemonics
- Remove vowels (except when type start with a
vowel) - Suppress duplicated consonants
- Suppress duplicated mnemonics by adding vowels
back - Examples
- edtAdress (type address)
- tblCustomer (type table)
- grpbxEmployee (type groupbox)
19Naming Conventions
- Names must be meaningful and descriptive
- Everything that will be used must be properly
named (Dont leave default names) - Distinguish parts by use of capitals
- Examples
- btnClientSave
- I, J,etc. (as counters)
20Naming Conventions
- Rules
- Variable names
- Lowercase
- Except for first letter of embedded words, which
must be uppercase - E.g. taxRate, numberOfLetters
- Subprogam, Object classes, Object variables and
method names - Must begin with uppercase letter
- Component names
- Start with prefix
- E.g. btnOK, edtInputValues
21Delphi Roadmap
- Delphi components
- Programming in Delphi
- Structured Programming
- Modular programming
- Object-oriented programming
- Standards
- Program design
- Programming steps
- Good programming practice
- Fundamental concepts and techniques
- Basic concepts
- Types of Applications
- Program Syntax
- Programming
22Program design
- Fundamental structure of a program is
- Input
- Process
- Output
23Program design
- Example 1 The Wastage program must work out the
wastage when a sheet of metal is cut into equal
sized parts.
edtLength
edtCutLength
edtWastage
24Program design
- Example 1 solution
- var
- totlength, cutlength, wastage integer
- begin
- totlength strtoint(edtLength.text)
- cutlength strtoint(edtCutLength.text)
- wastage totlength mod cutlength
- edtWastage.text inttostr(wastage)
- end
25Program design
- Step 1 Identify inputs and outputs
inputs
output
26Program design
- Step 2 Identify and declare variables and their
types - Input related variables
- totlength total length of metal
- cutlength cut length of metal
- Processing related variables
- wastage stores calculated wastage
- Output related variables
- None
- var
- totlength, cutlength, wastage integer
27Program design
- Step 2 Handle inputs
- // Input
- totlength strtoint(edtLength.text)
- cutlength strtoint(edtCutLength.text)
28Program design
- Step 3 Handle processing
- // Calculate wastage
- wastage totlength mod cutlength
29Program design
- Step 4 Handle output
- // Display wastage
- edtWastage.text inttostr(wastage)
30Program design
Example 1 solution with comments var totlength,
cutlength, wastage integer begin //Input totle
ngth strtoint(edtLength.text) cutlength
strtoint(edtCutLength.text) //Calculate
wastage wastage totlength mod
cutlength //Display wastage edtWastage.text
inttostr(wastage) end
31Program design
Example 1 An alternative solution var begin //C
alculate and display wastage edtWastage.text
inttostr (strtoint(edtLength.text) mod
strtoint(edtCutLength.text)) end
32Program design
Example 2 Read the input and display the
number of capital E s
edtInput
lblDisplay
33Program design
Example 2 Solution var wordent string
lenword, ecount, letpos integer begin
ecount 0 letpos 1 wordent
edtInput.text lenword length(edtInput.text)
repeat if copy(wordent,letpos,1) 'E'
then ecount ecount 1 letpos
letpos 1 until letpos gt lenword
lblDisplay.Caption Inttostr(ecount) end
34Program design
Example 2 Solution Step 1 (Identify inputs and
outputs)
Input
Output
35Program Design
- Step 2 Identify and declare variables and their
types - Input related variables
- wordent to store input word
- Processing related variables
- lenword stores the length of the word
- ecount stores the number of Es
- letpos stores the position of E
- Output related variables
- None
- var
- wordent string
- lenword, ecount, letpos integer
36Program Design
- Step 3 Handle input
- // Input
- wordent edtInput.text
37Program Design
- Step 4 Handle processing
- //Initialise
- ecount 0
- letpos 1
- lenword length(edtInput.text)
- //For every letter, see if it is a E. If it is,
add 1 to E-counter - repeat
- if copy(wordent,letpos,1) 'E' then
- ecount ecount 1
- letpos letpos 1
- until letpos gt lenword
-
38Program Design
- Step 4 Handle outputs
- //Display E-counter
- lblDisplay.Caption IntToStr(ecount)
-
-
39Delphi Roadmap
- Delphi components
- Programming in Delphi
- Modules
- Decisions
- Repetition
- Object-orientation
- Database
- Files
- Reports
- Interfacing
- Programming steps
- Good programming practice
- Fundamental concepts and techniques
- Basic concepts
- Types of Applications
- Program Syntax
- Programming
- Goto, Exit
- Procedures
- Functions
- Passing parameters
- Recursion
40Procedures and functions
- One of the ways of ensuring modular programming
is by using procedures and functions - They give a name to a group of statements that
accomplish a specific task - Difference between procedures and functions
- Function returns a value that may be used in an
expression
41Procedures and functions
- Make programs more readable, therefore less error
prone - Make programs easier to debug
- Code can be reused in other programs
- May be either standard (built-in) or user-defined
42Delphi Roadmap
- Delphi components
- Programming in Delphi
- Modules
- Decisions
- Repetition
- Object-orientation
- Database
- Files
- Reports
- Interfacing
- Programming steps
- Good programming practice
- Fundamental concepts and techniques
- Basic concepts
- Types of Applications
- Program Syntax
- Programming
- Goto, Exit
- Procedures
- Functions
- Passing parameters
- Recursion
43Goto and Exit
- Not part of structured programming
- But used in real programming
- It should be avoided, everything can be done with
structured control statements - If used, use in a controlled manner
44Goto
- Example
- procedure xxx
- label SmallSalary, BigSalary
- begin
- if Salary lt 1000 and Salary gt 0 then
- goto SmallSalary
- if Salary gt 1000 then
- goto BigSalary
- if Salary lt 0 then
- goto 9000
- SmallSalary
- WriteLn(Poor man)
- BigSalary
- WriteLn(Rich Man)
- 9000
- WriteLn(Wrong Input)
- end
-
PROBLEM!
45 Exit
- Example
- procedure xxx
- label SmallSalary, BigSalary
- begin
- if Salary lt 1000 and Salary gt 0 then
- goto SmallSalary
- if Salary gt 1000 then
- goto BigSalary
- if Salary lt 0 then
- goto 9000
- SmallSalary
- WriteLn(Poor man)
- Exit
- BigSalary
- WriteLn(Rich Man)
- Exit
- 9000
- WriteLn(Wrong Input)
46Goto and Exit
- Declaring labels
- label labelName1, , labelNamen
- Use a label
- labelName statement
- Unconditional branch (jump) to a label
- goto labelName
- Pass control immediately from current subprogram
to the calling program - Exit
47Delphi Roadmap
- Delphi components
- Programming in Delphi
- Modules
- Decisions
- Repetition
- Object-orientation
- Database
- Files
- Reports
- Interfacing
- Programming steps
- Good programming practice
- Fundamental concepts and techniques
- Basic concepts
- Types of Applications
- Program Syntax
- Programming
- Goto, Exit
- Procedures
- Functions
- Passing parameters
- Recursion
48Procedures
- May be used instead of a statement
- Structures a program to improve clarity and
generality
49Calling Procedures
- Procedure example 1
- Begin
- NumIn 16
- SquareRoot(NumIn,NumOut)
- SquareResult NumOut
- End
- SquareRoot is the name of a procedure
- NumIn and NumOut are the arguments of the
procedure - These arguments are passed to the procedure
- Executing the statement will execute the
corresponding procedure - This requires the procedure to be defined
beforehand -
50Defining Procedures
- Procedure example 1
- procedure SquareRoot(InValue real var OutValue
real) - begin
- OutValue sqrt(InValue)
- end
- Invalue and OutValue are the parameters of the
procedure - They correspond to the arguments passed
- The names of the arguments and parameters do not
have to be the same - They must however agree in type
- Order is important. The first argument
corresponds to the first parameter, the second
argument to the second parameter, etc. - These arguments can be any expression that is the
same type as the parameter
51Procedure flow of data
Begin NumIn 16 SquareRoot(NumIn,NumOut) Sq
uareResult NumOut End
procedure SquareRoot(InValue real var OutValue
real) begin OutValue sqrt(InValue) end
52Procedure flow of data
Begin NumIn 16 SquareRoot(NumIn,NumOut) Sq
uareResult NumOut End
procedure SquareRoot(InValue real var OutValue
real) begin OutValue sqrt(InValue) end
53Procedures
Exercise Create a procedure called TitleCase to
capitalize the first letter of every word in an
input sentence
54Procedures
55Delphi Roadmap
- Delphi components
- Programming in Delphi
- Modules
- Decisions
- Repetition
- Object-orientation
- Database
- Files
- Reports
- Interfacing
- Programming steps
- Good programming practice
- Fundamental concepts and techniques
- Basic concepts
- Types of Applications
- Program Syntax
- Programming
- Goto, Exit
- Procedures
- Functions
- Passing parameters
- Recursion
56Functions
- A function may be used instead of a variable
57Calling Functions
- Function example 1
- Begin
- NumIn 16
- SquareResult SquareRoot(NumIn,NumOut)
- End
- SquareRoot is the name of a function
- NumIn and NumOut are the arguments of the
function - These arguments are passed to the function
- Executing the statement will execute the
corresponding function - This requires the function to be defined
beforehand -
58Defining Functions
- Function example 1
- function SquareRoot(InValue real) real
- begin
- SquareRoot sqrt(InValue)
- end
- A function results in a value being assigned to
its name upon execution of that function - The value of the result of the function will be
of type real - The function identifier SquareRoot must be
assigned a value within the function block - The function identifier
- May not be used like a variable
- It may only be assigned a value
- It cannot be tested or accessed
- Invalue is the parameter of the function
59Function - flow of data
Begin NumIn 16 SquareResult
SquareRoot(NumIn) End
procedure SquareRoot(InValue real)
real begin SquareRoot sqrt(InValue) end
60Function - flow of data
Begin NumIn 16 SquareResult
SquareRoot(NumIn) End
procedure SquareRoot(InValue real)
real begin SquareRoot sqrt(InValue) end
61Functions
- Exercise
- Create a function to calculate the maximum value
of 5 integer values entered
62Functions
63Delphi Roadmap
- Delphi components
- Programming in Delphi
- Modules
- Decisions
- Repetition
- Object-orientation
- Database
- Files
- Reports
- Interfacing
- Programming steps
- Good programming practice
- Fundamental concepts and techniques
- Basic concepts
- Types of Applications
- Program Syntax
- Programming
- Goto, Exit
- Procedures
- Functions
- Passing parameters
- Recursion
64Passing parameters
- Parameters can be passed either
- By reference
- Actually passes address of argument, not
arguments value - Thus, subprogram can change argument variables
value - By value
- Passes value of argument to the subprogram
- Subprogram access copy of the argument variable
- Thus, subprogram cannot change value of variable
- Delphis default
65Passing parameters Pass by value
var value Integer begin value 5
WriteLn(Start Test value
IntToStr(value) TimesProcedure(value)
WriteLn(Start Test value
IntToStr(value) End
Output Start Test value
5 Start TimesProcedure number 5 End
TimesProcedure number 10 End Test
value 5
procedure TimesProcedure(number Integer) begin
WriteLn(Start TimesProcedure number
IntToStr(number) number number 2
WriteLn(End TimesProcedure number
IntToStr(number) end
66Passing parameters Pass by reference
Output Start Test value
5 Start TimesProcedure number 5 End
TimesProcedure number 10 End Test
value 10
var value Integer begin value 5
WriteLn(Start Test value
IntToStr(value) TimesProcedure(value)
WriteLn(Start Test value
IntToStr(value) End
procedure TimesProcedure(var number
Integer) begin WriteLn(Start TimesProcedure
number IntToStr(number) number
number 2 WriteLn(End TimesProcedure
number IntToStr(number) end
67Delphi Roadmap
- Delphi components
- Programming in Delphi
- Modules
- Decisions
- Repetition
- Object-orientation
- Database
- Files
- Reports
- Interfacing
- Programming steps
- Good programming practice
- Fundamental concepts and techniques
- Basic concepts
- Types of Applications
- Program Syntax
- Programming
68Decisions
- Two types of decisions
- Binary choice if
- Multiple choice case
69Delphi Roadmap
- Delphi components
- Programming in Delphi
- Modules
- Decisions
- Repetition
- Object-orientation
- Database
- Files
- Reports
- Interfacing
- Programming steps
- Good programming practice
- Fundamental concepts and techniques
- Basic concepts
- Types of Applications
- Program Syntax
- Programming
70If
Example 1 (If without an else) Graphical
representation
False
True
gender M
Display Male
71If
Example 1 (If without an else) Delphi
if gender M then Display Male
72If
Example 2 (If without an else) Graphical
representation
True
False
gender M
Display Male
Display Female
73If
Example 2 (If without an else) Delphi
if gender M then Display Male else Display
Female
74If
Example 3 (Multiple lines) Graphical
representation
True
False
gender M
Display Male Inc(maleCount)
Display Female Inc(femaleCount)
75If
Example 3 (Multiple lines) Delphi
if gender M then begin Display(Male) maleC
ount maleCount 1 end else
begin Display(Female) femaleCount
femaleCount 1 end
76If
Example 4 (else if) Graphical representation
True
sal lt 100
Display Small
False
sal gt 100 and sal lt 1000
True
Display Medium
False
True
sal gt 1000
Display Big
False
77If
Example 4 (else if) Delphi
if sal lt 100 then Display(Small) else if sal
gt 100 and sal lt 1000 Display(Medium) else if
sal gt 1000 Display(Big)
78If
Example 5 (nested if) Graphical representation
False
True
gender M
True
True
False
age lt 65
age lt 65
Display Mom
Display Grandma
Display Dad
Display Granddad
79If
Example 5 (nested if) Delphi
if gender M then if age lt 65
then Display(Dad) else
Display(Granddad) else if age lt 65
then Display(Mom) else
Display(Grandma)
80If
- Nested ifs
- The following code has two possible
interpretations - Rule each else is associated with the nearest
available if.
if exp1 then if exp2 then statement1 else
statement2
if exp1 then if exp2 then statement1
else statement2
if exp1 then if exp2 then statement1
else statement2
?
?
81If
- Hint
- Always use compound statements within your if
statement, even if you only have one statement in
it
82Delphi Roadmap
- Delphi components
- Programming in Delphi
- Modules
- Decisions
- Repetition
- Object-orientation
- Database
- Files
- Reports
- Interfacing
- Programming steps
- Good programming practice
- Fundamental concepts and techniques
- Basic concepts
- Types of Applications
- Program Syntax
- Programming
83Case
Example 1 Graphical representation
True
1..99
Display Small
False
True
Display Medium
100..999
sal
False
True
else
Display Big
False
84Case
Example 1 Delphi
case sal of 1..99
Display(Small) 100..999
Display(Medium) else
Display(Big) end
85Delphi Roadmap
- Delphi components
- Programming in Delphi
- Modules
- Decisions
- Repetition
- Object-orientation
- Database
- Files
- Reports
- Interfacing
- Programming steps
- Good programming practice
- Fundamental concepts and techniques
- Basic concepts
- Types of Applications
- Program Syntax
- Programming
86Repetition
- Example 1 Compute the sum of integers 1 - 10
Sum ? 0 Number ? 1
Sum ?Sum Number Number ?Number 1
NO
Number gt10?
YES
Display Sum
87Walkthroughs
Sum ? 0 Number ? 1
Sum ?Sum Number Number ?Number 1
NO
Number gt10?
YES
Display Sum
88Repetition
- Always involves
- Initialisation of values
- Incrementing of a counter or
- moving forward (e.g. next record in file)
- Testing of values
89Repetition
Sum ? 0 Number ? 1
Initialising values
Sum ?Sum Number Number ?Number 1
Incrementing values
NO
Testing values
Number gt10?
YES
Display Sum
90Repetition
- Delphi program of example 1
- var Sum, Number Integer
- begin
- Sum 0
- Number 1
- repeat
- Sum Sum Number
- Number Number 1
- until number gt 10
- writeln (Sum)
- end
91Repetition
Delphi program of example 1 var Sum, Number
Integer begin Sum 0 Number
1 repeat Sum Sum Number Number
Number 1 until number gt 10 writeln
(Sum) end
92Repetition
- Notes
- Number is the loop control variable or counter
variable in example 1 - The counter variable controls the number of times
the loop will execute - Always check the initial and end value of a
counter variable - Many times programmers make a mistake of one too
many or one too little times through the loop
93Exercise 1
- Make example 1 more general by allowing n (not
just 10) times through the loop and a variable
increment (not just 1)
94Exercise 1
- Flowchart and walkthrough (Yours)
95Exercise 1
Flowchart and walkthrough (Given)
96Exercise 1
Program