Lecture 05
Lecture 05
(C Programming Language)
Main program
Module 01 Module 02
Module A Module B
Program Modules in C
• Functions
▪ Modules in C
▪ Programs combine user-defined functions with library functions
− C standard library has a wide variety of functions
• Function calls
▪ Invoking functions
− Provide function name and arguments (data)
− Function performs operations or manipulations
− Function returns results
▪ Function call analogy:
− Boss asks worker to complete task
• Worker gets information, does task, returns result
• Information hiding: boss does not know details
Program Modules in C
• Familiarize yourself with the rich collection of functions in the C Standard Library.
• Avoid reinventing the wheel. When possible, use C Standard Library functions
instead of writing new functions. This can reduce program development time.
• Using the functions in the C Standard Library helps make programs more
portable.
Math Library Functions
#include <math.h>
• Format for calling functions
▪ FunctionName( argument );
− If multiple arguments, use comma-separated list
• Include the math header by using the preprocessor directive #include <math.h> when
using functions in the math library.
C Math Library Functions
C Math Library Functions
Functions
• Functions
▪ Modularize a program
▪ All variables defined inside functions are local variables
− Known only in function defined
▪ Parameters
− Communicate information between functions
− Local variables
• Benefits of functions
▪ Divide and conquer
− Manageable program development
▪ Software reusability
− Use existing functions as building blocks for new programs
− Abstraction - hide internal details (library functions)
▪ Avoid code repetition
Functions
Function definition
Functions
Function call
Function definition
Function Prototypes
• Function prototype
▪ Function name
▪ Parameters – what the function takes in
▪ Return type – data type function returns (default int)
▪ Used to validate functions
▪ Prototype only needed if function definition comes after use in program
▪ The function with the prototype
• Converting from a higher data type in the promotion hierarchy to a lower type can
change the data value.
• Forgetting a function prototype causes a syntax error.
• A function prototype placed outside any function definition applies to all calls to
the function appearing after the function prototype in the file.
• A function prototype placed in a function applies only to calls made in that
function.
Function Call Stack and Activation Records
• Header files
▪ Contain function prototypes for library functions
<stdlib.h>, <math.h>, etc
▪ Load with #include <filename>
#include <math.h>
• Call by value
▪ Copy of argument passed to function
▪ Changes in function do not effect original
▪ Use when function does not need to modify argument
− Avoids accidental changes
• Call by reference
▪ Passes original argument
▪ Changes in function effect original
▪ Only used with trusted functions
Generates a random
number between 1 and 6
Examples
Examples
Random Number Generation
• srand function
<stdlib.h>
▪ Takes an integer seed and jumps to that location in its "random" sequence
srand( seed );
▪ srand( time( NULL ) );/*load <time.h> */
− time( NULL )
− Returns the number of seconds that have passed since January 1, 1970
− “Randomizes" the seed
Examples
• Craps simulator
• Rules
▪ Roll two dices
− 7 or 11 on first throw, player wins
− 2, 3, or 12 on first throw, player loses
− 4, 5, 6, 8, 9, 10 - value becomes player's "point"
▪ Player must roll his point before rolling 7 to win
Examples: A Game of Chance
Examples: A Game of Chance
• Automatic storage
▪ Object created and destroyed within its block
▪ auto: default for local variables
auto double x, y;
▪ register: tries to put variable into high-speed registers
▪ Can only be used for automatic variables
register int counter = 1;
Storage Classes
• Static storage
▪ Variables exist for entire program execution
▪ Default value of zero
▪ static: local variables defined in functions.
− Keep value after function ends
− Only known in their own function
▪ extern: default for global variables and functions
− Known in any function
Scope Rules
• File scope
▪ Identifier defined outside function, known in all functions
▪ Used for global variables, function definitions, function prototypes
• Function scope
▪ Can only be referenced inside a function body
▪ Used only for labels (start:, case: , etc.)
Scope Rules
• Block scope
▪ Identifier declared inside a block
− Block scope begins at definition, ends at right brace
▪ Used for variables, function parameters (local variables of function)
▪ Outer blocks "hidden" from inner blocks if there is a variable with the same name in the inner
block
Global variable
Recursion
• Recursive functions
▪ Functions that call themselves
▪ Can only solve a base case
▪ Divide a problem up into
− What it can do
− What it cannot do
• What it cannot do resembles original problem
• The function launches a new copy of itself (recursion step) to solve what it cannot do
▪ Eventually base case gets solved
− Gets plugged in, works its way up and solves whole problem
Recursion
• Example: factorials
▪ 5! = 5 * 4 * 3 * 2 * 1
▪ Notice that
− 5! = 5 * 4!
− 4! = 4 * 3! ...
▪ Can compute factorials recursively
▪ Solve base case (1! = 0! = 1) then plug in
− 2! = 2 * 1! = 2 * 1 = 2;
− 3! = 3 * 2! = 3 * 2 = 6;
Recursion
Recursion
Recursion
• Repetition
▪ Iteration: explicit loop
▪ Recursion: repeated function calls
• Termination
▪ Iteration: loop condition fails
▪ Recursion: base case recognized
• Any problem that can be solved recursively can also be solved iteratively (nonrecursively).
• Avoid using recursion in performance situations. Recursive calls take time and
consume additional memory.
• Accidentally having a nonrecursive function call itself either directly, or indirectly
through another function.
• A heavily functionalized program—as compared to a monolithic (i.e., one-piece) program
without functions—makes potentially large numbers of function calls, and these consume
execution time on a computer’s processor(s).
Recursion
Exercises