functions a problem suppose we are writing a program that displays messages on the screen. we want...

64
Functions

Upload: pauline-crawford

Post on 28-Dec-2015

217 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Functions

Page 2: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

A Problem Suppose we are writing a program

that displays messages on the screen.

We want to display rows of =============================== to separate sections of output.

Page 3: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Solution#include <stdio.h>int main (void){ /* produce some output */ /* print banner line */ printf(“==============\n”) ; /* produce more output */ printf(“==============\n”); /* produce even more output */ printf(“==============\n”); /* produce final output */}

Page 4: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Critique Redundant code What if we want to change the

display e.g. to print a blank line before and

after each line with =’s ? What if we want to print banner

lines in some other program?

Page 5: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

The Solution: Functions Definition: A function is a named code

sequence A function can be executed by using its

name as a statement or expression. The function may have parameters -

information that can be different each time the function is executed.

The function may compute and return a value.

Page 6: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Why use functions ? Functions provide an abstraction when

writing a program - allow low-level details to be packaged.

Able to package a computation we need to perform at multiple spots within a program. Write once, use many times.

If changes are needed, they only have to be done once, in one place.

Page 7: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Why use functions ? Allows the programmer to create a

program from smaller, simpler sub-components.

Many programs are far too large to understand all at once.

Functions give us a way to break a large program into smaller pieces

A function should perform a well-defined task.

Page 8: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Common functionsmain (void){ . . . }

Function definitionfor main()

printf (“%d + %d is %d\n”,x,y,z);

scanf (“%d%d”, &x, &y) ;

limit = sqrt ((double) num);

Function calls

Page 9: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

More common functions Every standard C compiler comes with a

set of standard libraries. #include <stdio.h>

Tells the compiler you will use the standard IO library

#include <math.h> C’s standard math library functions:

sqrt, pow, sin, cos, exp, ...

isspace, ...

Page 10: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Defining your own functions You may define your own functions

in your programs You define a function by giving its

name and writing the code that is executed when the function is called.

Page 11: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Function definition

/* print banner line */void print_banner (void){

printf (“=========”);

printf (“=========\n”);

}

heading comment

function name

function body(statements to be executed)A function can haveANY number of ANYkind of statements

Page 12: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

/* print banner line */void print_banner (void){

printf (“=========”);

printf (“=========\n”);

}

voidvoid has two different roles in this function definition.

indicates that the functiondoes not return (have) anoutput value.

indicates that the functionhas no parameters.

Page 13: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Calling a functionint main (void){ /* produce some output */ . . . print_banner ();

/* produce more output */ . . . print_banner (); /* produce final output */ . . . print_banner ();}

To execute the function,it is called or invokedfrom within a program or another function.

Note: A function that does not return a value can be called wherever a statement is allowed.

Page 14: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Terminology main () is the caller print_banner() is the callee. main() invokes / calls

print_banner() 3 times. print_banner() is called from

main()

Page 15: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Function Control Flow/* print banner line */void print_banner (void){

printf(“**************\n”);

}

int main (void){ . . . print_banner (); . . . print_banner (); return (0);}

main (void){

print_banner ();

print_banner ();

}

print_banner {

}

print_banner {

}

Page 16: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Control Flow All C programs

Start at main () /*no matter where main()is */

Continue in top-to-bottom order, statement by statement, unless the order is changed by: function call function return if loops

Page 17: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Function Type and Value A function can return a value. Like all values in C, a function return value has a type. The function has the type of its returned value.

/* Get number from user */int get_input (void){ int num; printf (“Enter a number:”); scanf (“%d”, &num); return (num);}

function type

return statement

returned value

Page 18: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Calling a function A value-returning function is called

by including it in an expression.int main (void){ int x, y; x = get_input() ; y = get_input() ; printf (“ %d + %d = %d\n”, x, y, x+y); return (0);}

Note : A value returning function can be used anywhere an expression of the same type can be used.

Page 19: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

return In a value-returning function (result type is

not void) return does two distinct things : 1. specify the value returned by the execution

of the function 2. terminate that execution of the function.

In a void function: return is optional at the end of the function

body. return may also be used to terminate

execution of the function explicitly. No return value should appear following return.

Page 20: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

void compute_and_print_itax (){

double income;scanf (“%f”, &income);if (income < 50000) {

printf (“Income tax = Nil\n”); return;}if (income < 60000) {

printf (“Income tax = %f\n”, 0.1*(income-50000);return;

}if (income < 150000) {

printf (“Income tax = %f\n”, 0.2*(income-60000)+1000);

return ;}printf (“Income tax = %f\n”, 0.3*(income-150000)+19000);

}

Terminate function execution before reaching the end

Page 21: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Function parameters It is very often useful if a function can operate

on different data values each time it is called. Such values are function (input) parameters.

The function specifies its inputs as parameters in the function declaration.

/* Find area of a circle with radius r */double area (double r){

return (3.14159*r*r) ;}

parameter

Page 22: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Arguments The function call must include a matching

argument for each parameter. When the function is executed, the value of

the argument is substituted for the parameter.

int main (void){ . . .

double circum;. . .area1 = area(circum/2.0);. . .

}

double area (double r){

return (3.14*r*r);}

parameter passing

Page 23: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Control and data flow When a function is called:

(1) control transfers to the function body

(2) argument values are copied (3) the function executes (4) control and return value return to

the point of call.

Page 24: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Control and data flowint main (void){

double x, y, z;y=6.0;x = area(y/2.0);. . .z = area(7.88);. . .return (0);

}

double area (double r){

return (3.14*r*r);}

3.013.26

7.88

194.976

Page 25: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Style notes Put comments above a function body to

specify completely what the function does, including the significance of all the parameters.

/* Find area of a circle with radius r */double area (double r){

return (3.14159*r*r) ;}

Page 26: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Multiple parameters a function may have more than one parameter arguments must match parameters in number,

order and type.

void main (){

double x, y; int z; char op;

. . .z = operate (x, y, op);. . .

}

arguments

int operate (double x, double y, char op){

switch (op) { case ‘+’ : return x+y+0.5 ; case ‘~’ : if (x>y)

return x-y + 0.5; return y-x+0.5;

case ‘x’ : return x*y + 0.5; default : return –1;}

}parameters

Page 27: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Rules for using functions Arguments must match parameters:

in number in order in type

A function can only return one value. but it might contain more than one return

statement. In a function with return type T, the return

expression must be of type T. A function with return type T can be used

anywhere an expression of type T can be used.

Page 28: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Local variables A function can define its own local

variables. The locals have meaning only within the

function. Each execution of the function uses a new

set of locals Local variables cease to exist when the

function returns Parameters are also local.

Page 29: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Local variables

/* Find the area of a circle with diameter d */double circle_area (double d){

double radius, area;radius = d/2.0;area = 3.14*radius*radius;return (area);

}

parameterlocal variables

Page 30: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Defining function prototypes Functions should be declared

before they are used (invoked). Instead of writing the complete

function, you can use function prototypes to declare a function so that it can be used.

It is a good programming style to use function prototypes.

Page 31: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Function prototypesint operate (double x, double y, char op) ;int operate (double, double, char);void print_average (double, int);int get_intput (void);void print_banner (void);

•Write a function prototype near the top of the program•Can use the function anywhere thereafter.

Page 32: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

#define TRUE 1#define FALSE 0/* Find if x is a factor of y */int isFactor (int x, int y) { if (y%x == 0) return TRUE; return FALSE;}/* Rteurns true if x is a prime number */int isPrime (int x) { int factor; for (factor=2; factor <= sqrRt(x); factor++) if (isFactor(factor, x))

return FALSE; return FALSE; }/* Finds all prime numbers in acertain range */void main (void) { int i, start, limit; scanf (“%d%d”, &start,&limit); for (i=start; i<=limit; i++) { if (isPrime (i))

printf (“%d “, i); }}

Example :

Page 33: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Back to Arrays

Page 34: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Arrays as parameters of functions

An array passed as a parameter is not copied

Page 35: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Array operations#define MAXS 100int insert (int[], int, int, int) ;int delete (int[], int, int) ;int getelement (int[], int, int) ;int readarray (int[], int) ;main () {

int a[MAXS];int size;size = readarray (a, 10) ;size = insert (a, size, 4, 7) ;x = getelement (a, size, 3) ;size = delete (a, size, 3) ;

}

Page 36: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Array operations#define MAXS 100int insert (int[], int, int, int) ;int delete (int[], int, int) ;int getelement (int[], int, int) ;int readarray (int[], int) ;main () {

int a[MAXS];int size;size = readarray (a, 10) ;size = insert (a, size, 4, 7) ;x = getelement (a, size, 3) ;size = delete (a, size, 3) ;

}

int readarray (int x[], int size) { int i; for (i=0; i<size; i++)

scanf(“%d”, &x[i]) ; return size;}

int getelement (int x[], int size, int pos){ if (pos <size) return x[pos] ; return -1;}

int insert (int x[], int size, int pos. int val){ for (k=size; k>pos; k--)

x[k] = x[k-1] ; x[pos] = val ; return size+1;}

Page 37: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

void reverse (int x[], int size) {

}

int findmax (int x[], int size) {

}

Page 38: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

void reverse (int x[], int size) {

int i; for (i=0; i< (size/2); i++)

temp = x[size-i-1] ;x[size-1-1] = x[i] ;x[i] = temp;

}

int findmax (int x[], int size) {

int i, max; max = x[0];

for (i=1; i< size; i++)if (x[i] > max) max = x[i] ;

return max;}

Page 39: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Searching an Array:Linear and Binary Search

Page 40: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Searching Check if a given element (key)

occurs in the array. If the array is unsorted :

start at the beginning of the array inspect every element to see if it

matches the key

Page 41: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Linear Search

/* If key appears in a[0..size-1], return its location, pos, s.t. a[pos] == key. If key is not found, return -1 */

int search (int a[], int size, int key) {int pos = 0;while (pos < size && a[pos] != key)

pos++;if (pos<n)

return pos;return -1;

}

Page 42: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Linear Search

int x= {12,-3, 78,67,6,50,19,10} ;Trace the following calls :search (x, 8,6) ;search (x,8,5) ;

Page 43: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Searching a sorted array Binary search works if the array is

sorted Look for the target in the middle If you don’t find it, you can ignore half

of the array, and repeat the process with the other half.

Page 44: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Binary Search Strategy What we want : Find split betwen

values larger and smaller than x :

<=key >key

<=key ? >key

x:

x:

0n

L R

0 nL R

•Situation while searching :

•Step : Look at [(L+R)/2]. Move L or R to the middle depending on test.

Page 45: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Binary Search/* If key appears in x[0..size-1], return its location, pos s.t.

x[pos]==key. If not found, return -1 */int binsearch (int x[], int size, int key) {

int L, R, mid;______________________;while (_________________) {

}____________________ ;

}

Page 46: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

/* If key appears in x[0..size-1], return its location, pos s.t. x[pos]==key. If not found, return -1 */

int binsearch (int x[], int size, int key) {int L, R, mid;______________________;while (_________________) {

mid = (L+R)/2;if (x[mid] <= key) L = mid;else R = mid;

}____________________ ;

}

Binary Search

mid = (L+R)/2;if (x[mid] <= key) L = mid;else R = mid;

Page 47: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

/* If key appears in x[0..size-1], return its location, pos s.t. x[pos]==key. If not found, return -1 */

int binsearch (int x[], int size, int key) {int L, R, mid;______________________;while (_________________) {

mid = (L+R)/2;if (x[mid] <= key) L = mid;else R = mid;

}____________________ ;

}

Binary Search: loop termination

L+1 != R

Page 48: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

/* If key appears in x[0..size-1], return its location, pos s.t. x[pos]==key. If not found, return -1 */

int binsearch (int x[], int size, int key) {int L, R, mid;______________________;while ( L+1 != R) {

mid = (L+R)/2;if (x[mid] <= key) L = mid;else R = mid;

}

}

Binary Search: Return result

if (L>=0 && x[L]==key) return L;else return -1;

Page 49: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

/* If key appears in x[0..size-1], return its location, pos s.t. x[pos]==key. If not found, return -1 */

int binsearch (int x[], int size, int key) {int L, R, mid;______________________;while ( L+1 != R) {

mid = (L+R)/2;if (x[mid] <= key) L = mid;else R = mid;

}if (L>=0 && x[L]==key) return L;else return -1;

}

Binary Search: Initialization

L=-1; R=size;

Page 50: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Binary Search Examples

-17 -5 3 6 12 21 45 63 50

Trace :

binsearch (x, 9, 3);

binsearch (x, 9, 145);

binsearch (x, 9, 45);

Page 51: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Is it worth the trouble ? Suppose you had 1000 elements Ordinary search (if key is a member of x)

would require 500 comparisons on average. Binary search

after 1st compare, left with 500 elements after 2nd compare, left with 250 elements After at most 10 steps, you are done.

What if you had 1 million elements ?

Page 52: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Sorting Given an array x[0], x[1], ... ,

x[size-1] reorder entries so thatx[0]<=x[1]<= . . . <=x[size-1]

Page 53: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Sorting Problem What we want : Data sorted in order

sorted : x[0]<=x[1]<= . . . <=x[size-1]

x:

0 size

•Initial conditions :

unsortedx:

0 size

Page 54: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Selection Sort General situation :

remainder, unsortedsmallest elements, sorted0 siz

ek

•Step : •Find smallest element, mval, in x[k..size-1]•Swap smallest element with x[k], then increase k.

x:

smallest elements, sorted0 siz

ek

x:mval

Page 55: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Subproblem : : /* Yield location of smallest element int[x] in x[0 .. size-1];*/int min_loc (int x[], int , int size) int j, pos; /* x[pos] is the smallest element found so far */

pos = k; for (j=k+1; j<size; j++)

if (x[i] < x[pos])pos = j;

return pos;}

Page 56: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Selection Sort/* Sort x[0..size-1] in non-decreasing order */int selsort (int x[], int size) {

int k, m;for (k=0; k<size-1; k++) {

m = min_loc(x, k, size);temp = a[k];a[k] = a[m];a[m] = temp;

}}

Page 57: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Example

-1712 -5 6 14221 3 45x:

3 12 -5 6 14221-1745x:

-17 -5 12 6 14221 3 45x:

-17 -5 3 6 14221 12 45x:

-17 -5 3 6 12 2114245x:

-17 -5 3 6 12 2114245x:

-17 -5 3 6 12 21 45142x:

Page 58: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Analysis How many steps are needed to

sort n things ? Total number of steps proportional to

n2

Page 59: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Insertion Sort#define MAXN 100void InsertSort (int list[MAXN], int size) ;main () {

int index, size;int numbers[MAXN];/* Get Input */size = readarray (numbers) ;printarray (numbers, size) ;InsertSort (numbers, size) ;printarray (numbers, size) ;

}

Page 60: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

void InsertSort (int list[], int size) {for (i=1; i<size; i++)

item = list[i] ;for (j=i-1; (j>=0)&& (list[j] > i); j--)

list[j+1] = list[j];list[j+1] = item ;

}}

Page 61: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Common pitfalls with arrays in C Exceeding the array bounds

int array[10];for (i=0; i<=10; i++) array[i] = 0;

C does not support array declaratiions with variable expressions. void fun (int array, int size) {

int temp[size] ; . . .}

Page 62: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Local variables of main : i, start, limit

Parameters of isPrime : xLocal variables of isPrime : factor

Parameters of isFactor : x, y

Page 63: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Local Variables Formal parameters and variables declared

in a function are local to it. cannot be accessed or used by other functions

directly Allocated (created) on function entry. De-allocated (destroyed) on function return. Formal parameters initialized by copying

value of actual parameter. (“Call by value”)

Page 64: Functions A Problem Suppose we are writing a program that displays messages on the screen. We want to display rows of ======================== =======

Call by valuevoid printDouble (int x) {

printf (“Double of %d “, x); x *= 2;

printf (“is %d\n”, x) ;}void main () {

int num=15; printDouble (num); printf (“ num = %d\n”, num);

}

Note : The parameter of a function can be a constant, variable, expression – anything that has a value.

Only the value ispassed to the function.