UMBC CMSC 104 – Section 01, Fall 2016 Algorithms III
Notes & Announcements Project 2 due… now! Project 3 posted tonight Due next Thursday 10/13 at 5:30 PM
Writing Algorithms from Scratch Given a problem statement, we are going to write the corresponding generic algorithm for the solution. We will use the following procedure: Determine the algorithm inputs and outputs Pseudocode a rough algorithm Complete the pseudocode
The Cube Problem: Write an interactive program to compute and display the volume and surface area of a cube. The program must also display the cube dimensions. Error checking should be done to be sure that all cube dimensions are greater than zero.
The Cube: What Do We Know? We’re working with a cube. Cubes have equal length sides. Lets call our side length x. We need to calculate surface area of the cube. Cubes have 6 sides. 6x2 We need to calculate the volume of the cube. x3 We need to display the cube dimensions We need to verify that all dimensions are greater than zero
The Cube: Inputs & Outputs Side length Outputs Dimensions Surface Area Volume
The Cube: Rough Pseudocode Display “Enter the side length” Read <length> <surface area> = 6 * <length> * <length> <volume> = <length> * <length> * <length> Display “The dimensions are <length> x <length> x <length>” Display “The surface area is <surface area>” Display “The volume is <volume>”
The Cube: What are we missing? We’ve met all of our requirements, except ensuring all side lengths are greater than zero. How might we do this?
Control Structures Any problem can be solved using only three logical control structures: Sequence Selection Repetition
The Cube: Final Pseudocode Display “Enter the side length” Read <length> If (<length> is less than 1) Display “Invalid length! I quit!” Else <surface area> = 6 * <length> * <length> <volume> = <length> * <length> * <length> Display “The dimensions are <length> x <length> x <length>” Display “The surface area is <surface area>” Display “The volume is <volume>” End_If
The Cube: Final Pseudocode Display “Enter the side length” Read <length> While (<length> is less than 1) Display “Invalid length! Try again!” End_While <surface area> = 6 * <length> * <length> <volume> = <length> * <length> * <length> Display “The dimensions are <length> x <length> x <length>” Display “The surface area is <surface area>” Display “The volume is <volume>”
Drawing a Rectangle Problem: Write an interactive program that will draw a solid rectangle of asterisks (*). The program begins by prompting for dimensions. Error checking must be done to be sure that the dimensions are greater than zero.
A Solution… Display “Enter length” Read <length> Display “Enter width” Read <width> <length count> = 0 <width count> = 0 While (<length count> < <length>) While (<width count> < <width>) Display “*” <width count> = <width count> + 1 End_While Display Newline <length count> = <length count> + 1
Questions?