Download presentation
Presentation is loading. Please wait.
Published byClaud Rodgers Modified over 8 years ago
1
Designing Functions CSIS 1595: Fundamentals of Programming and Problem Solving 1
2
Modular Programming Breaking complex program down into simple functions – Easier to implement, test, and understand Tools: – Major steps in pseudocode used to design program Each major step separate function – Knowledge of typical functions programs often use Gathering and validating input Computing a complex value using conditions/loops Printing complex/formatted output …
3
Example: Balloon program Pseudocode: 1.Randomly generate and print the target distance 2.Prompt user for a velocity greater than 0 3.Prompt user for an angle in degrees and convert to radians 4.Compute distance balloon misses the target by 5.Determine whether the balloon hits and print the result
4
Function Design Functions in balloon program: – set_target() Generates random target distance, prints and returns it – get_velocity() Prompts for velocity until value > 0 entered, returning it – get_angle() Prompts for angle in degrees and converts to radians – compute_miss(target,velocity,angle) Computes the distance ballon flies and how much it misses the target by – print_result(miss_distance) Determines whether balloon hits and prints result
5
Function Design Common use: Computation to create single value – Limitation: Function can only return one value (more later)
6
Functions with No Arguments Many functions take no arguments – Common use: Getting input from user Syntax: def functionname(): – Still need to include () in the definition
7
Functions with No Return Value Function can return no value – Common use: Printing arguments in some complex way Syntax in function: – No return statement at all or just return with no expression Syntax of calling: functionname(arguments) – No return value to use in assignment
8
Structure of Main Program Often just consists mostly of function calls – Goal: Make main program very simple
9
Functions Calling Functions Functions can contain calls to other functions
10
Hierarchical Design Break program down into main tasks – These will be functions called from main program Break each main task down into subtasks – These will be “subfunctions” called from those functions … Continue until subtasks simple enough for functions
11
Hierarchical Design Example: Balloon table program Pseudocode: 1.Compute and print target distance 2.Prompt user for a velocity greater than 0 3.Loop angle from 0 to 45 every 3 degrees 1.Compute distance balloon misses target by 2.Print angle and result in column format Called by main program Called by loop function
12
Hierarchical Balloon Program
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.