algorithm design cs105. problem solving algorithm: set of unambiguous instructions to solve a...
Post on 21-Dec-2015
216 views
TRANSCRIPT
Algorithm Design
CS105
Problem Solving• Algorithm: set of unambiguous instructions to
solve a problem– Breaking down a problem into a set of sub-
problems– Example: Clean the house
• Without instructions – computers cannot do anything at all!
Algorithm design1. Analysis and specification
- Analyze: Understand/define the problem- Specify: Specify particulars
2. Algorithm development phase- Develop: Logical sequence of steps- Test: Follow outline, test cases
3. Implementation phase- Code: The steps into a programming language- Test: Debug
4. Maintenance phase- Use the program- Maintain: Correct errors, meet changing requirements
An example:
Variables
Output
An example:
Variables: A= loaf of bread K= knife T= toaster P= plate B= butter CB= cutting board
Making a perfect piece of toast
Version 21. move A to CB 2. cut S with K 3. move S to T 4. turn on T 5. wait for T 6. move S to P 7. spread B on S with K
S= slice of bread
move
move
move
An example:
Variables: A= loaf of bread K= knife T= toaster P= plate B= butter M= margarine F= friend CB= cutting board
Making toast for fussy friends: plain, butter, margarineVersion 3Move A to CBFOR every F eating toast{ Cut S with K Move S to T Turn on T Wait for T Move S to P IF F likes B { X=B } ELSE IF F likes M { X=M } ELSE { X= NOTHING } Spread X on S with K}
S= slice of breadX
Basic concepts• Example contains concepts used in most
algorithms• Instructions – simple and unambiguous• Variables – input and temporary• Subprocedures – smaller tasks• Looping: FOR each variable, WHILE– Act of repeating tasks
• Conditional statements: IF ELSE– Selectively execute instructions
Pseudocode: Flowchart• Flowchart: diagram that represents an
algorithm• Symbols:
START , END LOOPS, FLOW OF CONTROL
INSTRUCTIONS
CONDITIONALS
Pseudocode: FlowchartFixing non functioning lamp algorithm
Flowchart: Making toast for friends
Variables: A= loaf of breadK= knifeT= toasterP= plateB= butterM= margarineF= friend CB= cutting board
S= slice of breadX
Start Move A to CB Done?
Cut S with K
Move S to T
Turn on T
End
Wait for T
Move S to P
Want B?
Want M?
Set X to B
Set X to M
Set X to NONE
Spread X on S with K
Yes
NoYes
No
Yes
No
Start
End
Add 30 to X
Multiply X by 3
Is X > 100?
Is X < 80?
Subtract 15 from X
Print XYes
No
No
Yes
Divide X by 2Is X an integer
?
Yes
No Round it to the nearest integer
Add 30 to XIF ( x>100){
Subtract 15 from X}ELSE
{Multiply X by 3
}IF ( x<80){
PRINT X}ELSE
{ Divide X by 2 IF ( X is an integer) {
PRINT X } ELSE
{ Round X to the nearest integer
PRINT X
}
}
1. Add 30 to X2. IF X >100, subtract 153. ELSE multiply X by 34. IF X<80, PRINT X END5. ELSE Divide by 2
1. IF X is an integer, PRINT X END
2. ELSE round X, then PRINT X END