0% found this document useful (0 votes)
6 views

Lecture 05

Uploaded by

pltd2k6
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Lecture 05

Uploaded by

pltd2k6
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

Function

(C Programming Language)

Dr. Thien Huynh-The


Dept. Comp. Commun. Eng.
HCMC Technology and Education
Content

▪ Introduction ▪ Calling Functions: Call-by-Value and Call-


▪ Program Modules in C by- Reference
▪ Math Library Functions ▪ Random Number Generation

▪ Functions ▪ Example: A Game of Chance

▪ Function Definitions ▪ Storage Classes

▪ Function Prototypes ▪ Scope Rules

▪ Function Call Stack and Activation ▪ Recursion


Records ▪ Example Using Recursion: Fibonacci
▪ Headers Series
▪ Recursion vs. Iteration
Introduction

• Divide and conquer


▪ Construct a program from smaller pieces or components
− These smaller pieces are called modules
▪ Each piece more manageable than the original program

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

• Math library functions


▪ perform common mathematical calculations

#include <math.h>
• Format for calling functions
▪ FunctionName( argument );
− If multiple arguments, use comma-separated list

printf( "%.2f", sqrt( 900.0 ) );


− Calls function sqrt, which returns the square root of its argument
− All math functions return data type double
▪ Arguments may be constants, variables, or expressions

• 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

• In programs containing many functions, main is often implemented as a group of


calls to functions.
• Each function should be limited to performing a single, well-defined task, and the
function name should effectively express that task.
• If you cannot choose a concise name that expresses what the function does, it is
possible that your function is attempting to perform too many diverse tasks.
Function Definitions

• Function definition format


return-value-type function-name( parameter-list )
{
declarations and statements
}
▪ Function-name: any valid identifier
▪ Return-value-type: data type of the result (default int)
− void – indicates that the function returns nothing
▪ Parameter-list: comma separated list, declares parameters
− A type must be listed explicitly for each parameter unless, the parameter is of type int
Function Definitions

• Function definition format (continued)


return-value-type function-name( parameter-list )
{
declarations and statements
}
▪ Definitions and statements: function body (block)
− Variables can be defined inside blocks (can be nested)
− Functions can not be defined inside other functions
▪ Returning control
− If nothing returned
return;
or, until reaches right brace
− If something returned
return expression;
Examples

Function prototype indicates


function will be defined later in the
program

Call to square function

Function definition
Functions

• Place a blank line between function definitions


• Defining a function inside another function is a syntax error
• Omitting the return-value-type in a function definition is a syntax error
• Forgetting to return a value from a function that is supposed to return a value can lead to
unexpected errors
• Returning a value from a function with a void return type is a syntax error.
• Even though an omitted return type defaults to int, always state the return type explicitly.
double x, double y is different with double x, y
• Consider dividing the function into smaller functions
Examples
Function prototype

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

int maximum( int x, int y, int z );


− Takes in 3 ints
− Returns an int

• Promotion rules and conversions


▪ Converting to lower types can lead to errors
Function

• Use #include preprocessor directives to obtain function prototypes for the


standard library functions
• Parameter names are sometimes included in function prototypes (our preference)
for documentation purposes.
• Forgetting the semicolon at the end of a function prototype is a syntax error.
Data Types
Data Types
Data Types

• 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

• Program execution stack


▪ A stack is a last-in, first-out (LIFO) data structure
− Anything put into the stack is placed “on top”
− The only data that can be taken out is the data on top
▪ C uses a program execution stack to keep track of which functions have been called
− When a function is called, it is placed on top of the stack
− When a function ends, it is taken off the stack and control returns to the function immediately below it
▪ Calling more functions than C can handle at once is known as a “stack overflow error”
Headers

• Header files
▪ Contain function prototypes for library functions
<stdlib.h>, <math.h>, etc
▪ Load with #include <filename>
#include <math.h>

• Custom header files


▪ Create file with functions
▪ Save as filename.h
▪ Load in other files with #include "filename.h"
▪ Reuse functions
Headers
Headers
Calling Functions

• 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

• For now, we focus on call by value


Random Number Generation
• rand function
▪ Load <stdlib.h>
▪ Returns "random" number between 0 and RAND_MAX (at least 32767)
i = rand();
▪ Pseudorandom
− Preset sequence of "random" numbers
− Same sequence for every function call
• Scaling
▪ To get a random number between 1 and n
1 + ( rand() % n )
− rand() %n returns a number between 0 and n - 1
− Add 1 to make random number between 1 and n
1 + ( rand() % 6)
• number between 1 and 6
Random Number Generation

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

Seeds the rand function

Error: Using srand in place of


rand to generate random numbers.
Examples: A Game of Chance

• 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

enum (enumeration) assigns


numerical values to
CONTINUE, WON, and LOST
Examples: A Game of Chance
Examples: A Game of Chance
Storage Classes

• Storage class specifiers


▪ Storage duration – how long an object exists in memory
▪ Scope – where object can be referenced in program
▪ Linkage – specifies the files in which an identifier is known

• 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

• Function prototype scope


▪ Used for identifiers in parameter list
Scope Rules

Global variable with file scope

Variable with block scope

Variable with block scope

Variable with block scope


Scope Rules

Static variable with block scope

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

• Forgetting to return a value from a recursive function when one is needed.


• Either omitting the base case, or writing the recursion step incorrectly so that it
does not converge on the base case, will cause infinite recursion, eventually
exhausting memory.
Examples: Fibonacci Series

• Fibonacci series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …


▪ Each number is the sum of the previous two
▪ Can be solved recursively:
fib( n ) = fib( n - 1 ) + fib( n – 2 )
• Code for the fibonacci function
long fibonacci( long n )
{
if (n == 0 || n == 1) // base case
return n;
else
return fibonacci( n - 1) +
fibonacci( n – 2 );
}
Examples: Fibonacci Series
Examples: Fibonacci Series
Recursion

• Writing programs that depend on the order of evaluation of the operands of


operators other than &&, ||, ?:, and the comma (,) operator can lead to errors
• Programs that depend on the order of evaluation of the operands of operators
other than &&, ||, ?:, and the comma (,) operator can function differently on
systems with different compilers.
• Avoid Fibonacci-style recursive programs which result in an exponential
“explosion” of calls.
Recursion vs Iteration

• Repetition
▪ Iteration: explicit loop
▪ Recursion: repeated function calls

• Termination
▪ Iteration: loop condition fails
▪ Recursion: base case recognized

• Both can have infinite loops


• Balance
▪ Choice between performance (iteration) and good software engineering (recursion
Recursion

• 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

• Viết chtrình trong đó có hàm tự định nghĩa xác định số nguyên tố


▪ Nhập vào 1 số nguyên dương. Kiểm tra số đó có phải có nguyên tố hay ko?
▪ Tiếp tục nhập vào khoảng giá trị [a,b]. Tìm và in ra tất cả các số nguyên tố có trong khoảng đó

• Viết chtrình sử dụng hàm tự định nghĩa


▪ Nhập vào 1 số nguyên dương. Kiểm tra số đó có phải là số amstrong
Ví dụ:
− 4 = 41
− 371 = 33+73+13
− 1634=14+64+34+44
▪ Nhập vào 1 số nguyên dương. Kiểm tra số đó có phải là số hoàn hảo
Ví dụ: 6=1+2+3 (6 = tổng các ước số của nó – ngoại trừ chính nó)
28=1+2+4+7+14

You might also like