Developing Algorithms

  • When creating an algorithm, its good to outline its process before coding
    • This ensures that it is sequenced correctly
  • You should represent the algorithm using a flowchart or natural language
    • Visualization can help you better see the flow of the whole algorithm
    • This may allow for the coding process to be more efficient and effective

Review of Selection and Iteration

  • Algorithms with iteration repeat a function until a goal is reached
    • To more easily represent an algorithm without showing all the repeated steps, we can use iteration
  • Algorithms with selection only go through certain functions if certain things are true or false

Example 1

  1. Start
  2. The number of pretzels in the pack is 6
  3. Eat one fruit snack, number of pretzels in pack goes down by 1
  4. How many pretzels are left?
  5. Repeat step 3 until number of pretzels is 0
  6. Display that pack is empty
  7. Finish
pretzel = 6
while (pretzel > 0):
    pretzel -= 1
    print(pretzel)
    if pretzel == 0:
        print("All done!")
5
4
3
2
1
0
All done!

Example 2

The parking rate for a garage is as follows:
Less than one hour: Free
1-2 hours: $5 <br> 2-3 hours: $8
3-4 hours: $10 <br> 4+ hours: $12

  1. Start
  2. Input number of hours parked
  3. If hours is less than 1, cost is free
  4. If hours is between 1 and 2, cost is $5
  5. If hours is between 2 and 3, cost is $8
  6. If hours is between 3 and 4, cost is $10
  7. If hours is more than 4, cost is $12
  8. Display cost and goodbye
  9. Finish
print("The parking rate is as follows: \n Less than one hour: Free \n 1-2 hours: $5 \n 2-3 hours: $8 \n 3-4 hours: $10 \n 4+ hours: $12")

time = float(input("How many hours have you parked at this garage?"))
print("How many hours have you parked at this garage?")
print(time, "hours costs:")

if time < 1 :
    print("Free")
elif time >= 1 and time < 2 :
    print("$5")
elif time >= 2 and time < 3 :
    print("$8")
elif time >= 3 and time < 4 :
    print("$10")
else:
    print("$12")

print("Have a good day!")

Hacks

Develop your own complex algorithm using a flowchart and natural language, then code it!

Requirements:

  • Includes both a flowchart AND natural language
  • Working code of the same algorithm
  • Incorporates selection AND/OR iteration
  • Make it creative!

Tips:

  • This site is good for making flowcharts!
  • Natural language should just be a list
  • Think about the whole process, not just the end result