35
Functions CSE 251 Dr. Charles B. Owen Programming in C 1

Functions - Michigan State Universitycse251/lecture6.pdfCSE 251 Dr. Charles B. Owen 2 Programming in C Triangle Area Computation a = p2 −p1 p2=(x2 y2) p3=(x3,y3) 3 2 3 1 c p p b

  • Upload
    others

  • View
    3

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Functions - Michigan State Universitycse251/lecture6.pdfCSE 251 Dr. Charles B. Owen 2 Programming in C Triangle Area Computation a = p2 −p1 p2=(x2 y2) p3=(x3,y3) 3 2 3 1 c p p b

Functions

CSE 251 Dr. Charles B. OwenProgramming in C1

Page 2: Functions - Michigan State Universitycse251/lecture6.pdfCSE 251 Dr. Charles B. Owen 2 Programming in C Triangle Area Computation a = p2 −p1 p2=(x2 y2) p3=(x3,y3) 3 2 3 1 c p p b

Moon Landings

Time Fuel Velocity

Will Cyr 13 86.20 ‐0.49

Yongjiao Yu 13 86.00 ‐1.82

Bin Tian 13 87 00 ‐1 69Bin Tian 13 87.00 ‐1.69

Nan Xia 13 87.00 ‐1.69

Chenli Yuan 13 87.00 ‐1.69

Scott Oliver 13 87.70 ‐2.74

Mike Robell 13 87.88 ‐3.00

CSE 251 Dr. Charles B. OwenProgramming in C2

Page 3: Functions - Michigan State Universitycse251/lecture6.pdfCSE 251 Dr. Charles B. Owen 2 Programming in C Triangle Area Computation a = p2 −p1 p2=(x2 y2) p3=(x3,y3) 3 2 3 1 c p p b

Triangle Area Computation 12 ppa −=

p2=(x2 y2)

p3=(x3,y3)23

13

ppc

ppb

−=

−=c

p2=(x2,y2)

ab

22 )12()12( yyxxa −+−=

p1=(x1,y1) ))()((cba

cpbpapparea++

−−−=

2cbap ++

=

How would you write this program?

CSE 251 Dr. Charles B. OwenProgramming in C3

Page 4: Functions - Michigan State Universitycse251/lecture6.pdfCSE 251 Dr. Charles B. Owen 2 Programming in C Triangle Area Computation a = p2 −p1 p2=(x2 y2) p3=(x3,y3) 3 2 3 1 c p p b

Variablesint main(){

double x1=0 y1=0;double x1=0, y1=0;double x2=17, y2=10.3;double x3=‐5.2, y3=5.1;

double a, b, c;     /* Triangle side lengths */double p;           /* For Heron's formula */double area;

12 ppa −=

23

13

ppc

ppb

pp

−=

−=

pp

22 )12()12( yyxxa −+−=

CSE 251 Dr. Charles B. OwenProgramming in C4

Page 5: Functions - Michigan State Universitycse251/lecture6.pdfCSE 251 Dr. Charles B. Owen 2 Programming in C Triangle Area Computation a = p2 −p1 p2=(x2 y2) p3=(x3,y3) 3 2 3 1 c p p b

Lengths of Edges

a = sqrt((x1 ‐ x2) * (x1 ‐ x2) + (y1 ‐ y2) * (y1 ‐ y2));b = sqrt((x1 ‐ x3) * (x1 ‐ x3) + (y1 ‐ y3) * (y1 ‐ y3));c = sqrt((x2 ‐ x3) * (x2 ‐ x3) + (y2 ‐ y3) * (y2 ‐ y3));

13

12

ppb

ppa

−=

−=

23 ppc −=

22p2=(x2,y2)

p3=(x3,y3)c

22 )12()12( yyxxa −+−=

ab

))()(( cpbpapparea =p1=(x1,y1)

2

))()((cbap

cpbpapparea++

=

−−−=

CSE 251 Dr. Charles B. OwenProgramming in C5

Page 6: Functions - Michigan State Universitycse251/lecture6.pdfCSE 251 Dr. Charles B. Owen 2 Programming in C Triangle Area Computation a = p2 −p1 p2=(x2 y2) p3=(x3,y3) 3 2 3 1 c p p b

Areap = (a + b + c) / 2;area = sqrt(p * (p ‐ a) * (p ‐ b) * (p ‐ c));q (p (p ) (p ) (p ));

printf("%f\n", area); ))()(( cpbpapparea −−−= ))()(( cpbpapparea −−−=

2cbap ++

=2

cbap ++=

CSE 251 Dr. Charles B. OwenProgramming in C6

Page 7: Functions - Michigan State Universitycse251/lecture6.pdfCSE 251 Dr. Charles B. Owen 2 Programming in C Triangle Area Computation a = p2 −p1 p2=(x2 y2) p3=(x3,y3) 3 2 3 1 c p p b

Whole Programint main(){

double x1=0, y1=0;Wh if I d i kdouble x2=17, y2=10.3;

double x3=‐5.2, y3=5.1;

double a, b, c; /* Triangle side lengths */

What if I made a mistake on the edge length equation?

double a, b, c;     /  Triangle side lengths  /double p;           /* For Heron's formula */double area;

t(( 1 2) * ( 1 2) ( 1 2) * ( 1 2))a = sqrt((x1 ‐ x2) * (x1 ‐ x2) + (y1 ‐ y2) * (y1 ‐ y2));b = sqrt((x1 ‐ x3) * (x1 ‐ x3) + (y1 ‐ y3) * (y1 ‐ y3));c = sqrt((x2 ‐ x3) * (x2 ‐ x3) + (y2 ‐ y3) * (y2 ‐ y3));

p = (a + b + c) / 2;area = sqrt(p * (p ‐ a) * (p ‐ b) * (p ‐ c));

printf("%f\n" area);printf( %f\n , area);}

CSE 251 Dr. Charles B. OwenProgramming in C7

Page 8: Functions - Michigan State Universitycse251/lecture6.pdfCSE 251 Dr. Charles B. Owen 2 Programming in C Triangle Area Computation a = p2 −p1 p2=(x2 y2) p3=(x3,y3) 3 2 3 1 c p p b

Functions

• Functions are subprograms that perform some operation and return one value

• They “encapsulate” some particular operation, so it can be re‐used by others (for example, the abs() or 

() f i )sqrt() function)

CSE 251 Dr. Charles B. OwenProgramming in C8

Page 9: Functions - Michigan State Universitycse251/lecture6.pdfCSE 251 Dr. Charles B. Owen 2 Programming in C Triangle Area Computation a = p2 −p1 p2=(x2 y2) p3=(x3,y3) 3 2 3 1 c p p b

Characteristics

• Reusable code– code in sqrt() is reused often

• Encapsulated code– implementation of sqrt() is hidden

• Can be stored in libraries– sqrt() is a built‐in function found in the math library

CSE 251 Dr. Charles B. OwenProgramming in C9

Page 10: Functions - Michigan State Universitycse251/lecture6.pdfCSE 251 Dr. Charles B. Owen 2 Programming in C Triangle Area Computation a = p2 −p1 p2=(x2 y2) p3=(x3,y3) 3 2 3 1 c p p b

Writing Your Own Functions

• Consider a function that converts temperatures in Celsius to temperatures in Fahrenheit.– Mathematical Formula:   

F C * 1 8 32 0F = C * 1.8 + 32.0

– We want to write a C function called CtoF– We want to write a C function called CtoF

CSE 251 Dr. Charles B. OwenProgramming in C10

Page 11: Functions - Michigan State Universitycse251/lecture6.pdfCSE 251 Dr. Charles B. Owen 2 Programming in C Triangle Area Computation a = p2 −p1 p2=(x2 y2) p3=(x3,y3) 3 2 3 1 c p p b

Convert Function in C

double CtoF ( double paramCel ) {                                                      

return paramCel*1.8 + 32.0;                                }

• This function takes an input parameter called paramCel (temp in degree Celsius) and returns aparamCel (temp in degree Celsius) and returns a value that corresponds to the temp in degree Fahrenheita e e

CSE 251 Dr. Charles B. OwenProgramming in C11

Page 12: Functions - Michigan State Universitycse251/lecture6.pdfCSE 251 Dr. Charles B. Owen 2 Programming in C Triangle Area Computation a = p2 −p1 p2=(x2 y2) p3=(x3,y3) 3 2 3 1 c p p b

How to use a function?

#include <stdio.h>

double CtoF( double );

/************************************************************************* Purpose: to convert temperature from Celsius to Fahrenheit ************************************************************************/int main() {

double c, f;printf(“Enter the degree (in Celsius): “);scanf(“%lf”, &c); 

f = CtoF(c);printf(“Temperature (in Fahrenheit) is %lf\n”, f);

}

double CtoF ( double paramCel) {

return paramCel * 1.8 + 32.0;}}

CSE 251 Dr. Charles B. OwenProgramming in C12

Page 13: Functions - Michigan State Universitycse251/lecture6.pdfCSE 251 Dr. Charles B. Owen 2 Programming in C Triangle Area Computation a = p2 −p1 p2=(x2 y2) p3=(x3,y3) 3 2 3 1 c p p b

TerminologyD l ti d bl Ct F( d bl )• Declaration:  double CtoF( double );

• Invocation (Call): Fahr CtoF(Cel);• Invocation (Call):    Fahr = CtoF(Cel);

• Definition:• Definition:                                      double CtoF( double paramCel ) {{                                                        return paramCel*1.8 + 32.0;                                  

}}

CSE 251 Dr. Charles B. OwenProgramming in C13

Page 14: Functions - Michigan State Universitycse251/lecture6.pdfCSE 251 Dr. Charles B. Owen 2 Programming in C Triangle Area Computation a = p2 −p1 p2=(x2 y2) p3=(x3,y3) 3 2 3 1 c p p b

Function Declarationl ll d f• Also called function prototype:

return_type function_name (parameter_list)

double CtoF(double)• Declarations describe the function:

– the return type and function name

( )

– the type and number of parameters 

CSE 251 Dr. Charles B. OwenProgramming in C14

Page 15: Functions - Michigan State Universitycse251/lecture6.pdfCSE 251 Dr. Charles B. Owen 2 Programming in C Triangle Area Computation a = p2 −p1 p2=(x2 y2) p3=(x3,y3) 3 2 3 1 c p p b

Function Definition

return_type function_name (parameter_list) {

….function body….

}

double CtoF(double paramCel) {{

return paramCel*1.8 + 32.0;}

CSE 251 Dr. Charles B. OwenProgramming in C15

Page 16: Functions - Michigan State Universitycse251/lecture6.pdfCSE 251 Dr. Charles B. Owen 2 Programming in C Triangle Area Computation a = p2 −p1 p2=(x2 y2) p3=(x3,y3) 3 2 3 1 c p p b

Function Invocation1 C ll i

int main() { …f = CtoF(c);

1. Call copies argument c to

tf CtoF(c); } parameter

paramCel

double CtoF ( double paramCel ){

2. Control f {

return paramCel*1.8 + 32.0;}

transfers to function “C F”“CtoF”

CSE 251 Dr. Charles B. OwenProgramming in C16

Page 17: Functions - Michigan State Universitycse251/lecture6.pdfCSE 251 Dr. Charles B. Owen 2 Programming in C Triangle Area Computation a = p2 −p1 p2=(x2 y2) p3=(x3,y3) 3 2 3 1 c p p b

Invocation (cont)

int main() { …

f = CtoF(c); }

3. Expression in “CtoF” is

} evaluated

double CtoF ( double paramCel ){

return paramCel*1 8 + 32 0;

4. Value of expression return paramCel*1.8 + 32.0;

}expression is returned to “main”to main

CSE 251 Dr. Charles B. OwenProgramming in C17

Page 18: Functions - Michigan State Universitycse251/lecture6.pdfCSE 251 Dr. Charles B. Owen 2 Programming in C Triangle Area Computation a = p2 −p1 p2=(x2 y2) p3=(x3,y3) 3 2 3 1 c p p b

Local Objects

• The parameter “paramCel” is a local object which is defined only while the function is executing.  Any attempt to use “paramCel” outside the function is an error.

• The name of the parameter need not be the same as th f th t T tthe name of the argument.  Types must agree.

CSE 251 Dr. Charles B. OwenProgramming in C18

Page 19: Functions - Michigan State Universitycse251/lecture6.pdfCSE 251 Dr. Charles B. Owen 2 Programming in C Triangle Area Computation a = p2 −p1 p2=(x2 y2) p3=(x3,y3) 3 2 3 1 c p p b

Can we do better than this?

int main(){double x1=0, y1=0;double x2 17 y2 10 3double x2=17, y2=10.3;double x3=‐5.2, y3=5.1;

double a, b, c;     /* Triangle side lengths */double p;           /* For Heron's formula */double area;

a = sqrt((x1 x2) * (x1 x2) + (y1 y2) * (y1 y2));a = sqrt((x1 ‐ x2)   (x1 ‐ x2) + (y1 ‐ y2)   (y1 ‐ y2));b = sqrt((x1 ‐ x3) * (x1 ‐ x3) + (y1 ‐ y3) * (y1 ‐ y3));c = sqrt((x2 ‐ x3) * (x2 ‐ x3) + (y2 ‐ y3) * (y2 ‐ y3));

p = (a + b + c) / 2;area = sqrt(p * (p ‐ a) * (p ‐ b) * (p ‐ c));

printf("%f\n" area);printf( %f\n , area);}

CSE 251 Dr. Charles B. OwenProgramming in C19

Page 20: Functions - Michigan State Universitycse251/lecture6.pdfCSE 251 Dr. Charles B. Owen 2 Programming in C Triangle Area Computation a = p2 −p1 p2=(x2 y2) p3=(x3,y3) 3 2 3 1 c p p b

What should we name our function?a = sqrt((x1 ‐ x2) * (x1 ‐ x2) + (y1 ‐ y2) * (y1 ‐ y2));

“Length” sounds like a good ideaLength  sounds like a good idea.

???   Length(  ???  ){{}

CSE 251 Dr. Charles B. OwenProgramming in C20

Page 21: Functions - Michigan State Universitycse251/lecture6.pdfCSE 251 Dr. Charles B. Owen 2 Programming in C Triangle Area Computation a = p2 −p1 p2=(x2 y2) p3=(x3,y3) 3 2 3 1 c p p b

What does our function need to know?a = sqrt((x1 ‐ x2) * (x1 ‐ x2) + (y1 ‐ y2) * (y1 ‐ y2));

(x, y) for two different points: 

???   Length(double x1, double y1, double x2, double y2)

{{}

CSE 251 Dr. Charles B. OwenProgramming in C21

Page 22: Functions - Michigan State Universitycse251/lecture6.pdfCSE 251 Dr. Charles B. Owen 2 Programming in C Triangle Area Computation a = p2 −p1 p2=(x2 y2) p3=(x3,y3) 3 2 3 1 c p p b

What does our function return?a = sqrt((x1 ‐ x2) * (x1 ‐ x2) + (y1 ‐ y2) * (y1 ‐ y2));

A computed value which is of type double

double Length(double x1, double y1, double x2, double y2)

{{}

CSE 251 Dr. Charles B. OwenProgramming in C22

Page 23: Functions - Michigan State Universitycse251/lecture6.pdfCSE 251 Dr. Charles B. Owen 2 Programming in C Triangle Area Computation a = p2 −p1 p2=(x2 y2) p3=(x3,y3) 3 2 3 1 c p p b

How does it compute it?a = sqrt((x1 ‐ x2) * (x1 ‐ x2) + (y1 ‐ y2) * (y1 ‐ y2));

A computed value which is of type double

double Length(double x1, double y1, double x2, double y2)

{{double len;len = sqrt((x1 ‐ x2) * (x1 ‐ x2) + (y1 ‐ y2) * (y1 ‐ y2));return(len);return(len);

}

CSE 251 Dr. Charles B. OwenProgramming in C23

Page 24: Functions - Michigan State Universitycse251/lecture6.pdfCSE 251 Dr. Charles B. Owen 2 Programming in C Triangle Area Computation a = p2 −p1 p2=(x2 y2) p3=(x3,y3) 3 2 3 1 c p p b

Using This#include <stdio.h>#include <math.h>

/* Declaration */double Length(double x1, double y1, double x2, double y2);

/* * Program to determine the area of a triangle*/

int main(){

Declaration

{double x1=0, y1=0;double x2=17, y2=10.3;double x3=‐5.2, y3=5.1;

double a, b, c;     /* Triangle side lengths */d bl /* ' f l */double p;           /* For Heron's formula */double area;

a = Length(x1, y1, x2, y2);b = Length(x1, y1, x3, y3);c = Length(x2, y2, x3, y3);

Invocations

p = (a + b + c) / 2;area = sqrt(p * (p ‐ a) * (p ‐ b) * (p ‐ c));

printf("%f\n", area);}}

/* Definition */double Length(double x1, double y1, double x2, double y2){

double len;len = sqrt((x1 ‐ x2) * (x1 ‐ x2) + (y1 ‐ y2) * (y1 ‐ y2));

Definition

CSE 251 Dr. Charles B. OwenProgramming in C24

len   sqrt((x1  x2)   (x1  x2)   (y1  y2)   (y1  y2));return(len);

}

1

Page 25: Functions - Michigan State Universitycse251/lecture6.pdfCSE 251 Dr. Charles B. Owen 2 Programming in C Triangle Area Computation a = p2 −p1 p2=(x2 y2) p3=(x3,y3) 3 2 3 1 c p p b

Potential Errors#include <stdio.h>double convert( double );

int main()int main() {

double c, f;printf(“Enter the degree (in Celsius): “);scanf(“%lf”, &c);scanf( %lf , &c); f= convert(c);printf(“Temp (in Fahrenheit) for %lf Celsius is %lf”, paramCel, f);

} Error! paramCel is not defined

double CtoF( double paramCel) {

return c * 1.8 + 32.0;} Error! C is not defined

Scope – Where a variable is known to existError! C is not defined known to exist.

No variable is known outside of the curly braces that contain it, even if the same name is used!

CSE 251 Dr. Charles B. OwenProgramming in C25

Page 26: Functions - Michigan State Universitycse251/lecture6.pdfCSE 251 Dr. Charles B. Owen 2 Programming in C Triangle Area Computation a = p2 −p1 p2=(x2 y2) p3=(x3,y3) 3 2 3 1 c p p b

Another Example

#include <stdio.h>

double GetTemperature();p ();double CelsiusToFahrenheit( double );void DisplayResult( double, double );

int main()

Declarationsint main(){

doubleTempC,                 // Temperature in degrees CelsiusTempF;                 // Temperature in degrees Fahrenheit

TempC = GetTemperature();TempF = CelsiusToFahrenheit(TempC); InvocationsTempF = CelsiusToFahrenheit(TempC);DisplayResult(TempC, TempF); 

return 0;}  

CSE 251 Dr. Charles B. OwenProgramming in C26

Page 27: Functions - Michigan State Universitycse251/lecture6.pdfCSE 251 Dr. Charles B. Owen 2 Programming in C Triangle Area Computation a = p2 −p1 p2=(x2 y2) p3=(x3,y3) 3 2 3 1 c p p b

Function:GetTemperature

double GetTemperature(){

double Temp;p;

printf("\nPlease enter a temperature in degrees Celsius: ");scanf("%lf", &Temp);return Temp;return Temp;

}

CSE 251 Dr. Charles B. OwenProgramming in C27

Page 28: Functions - Michigan State Universitycse251/lecture6.pdfCSE 251 Dr. Charles B. Owen 2 Programming in C Triangle Area Computation a = p2 −p1 p2=(x2 y2) p3=(x3,y3) 3 2 3 1 c p p b

Function: CelsiusToFahrenheitdouble CelsiusToFahrenheit(double Temp){

return (Temp * 1.8 + 32.0);}}

CSE 251 Dr. Charles B. OwenProgramming in C28

Page 29: Functions - Michigan State Universitycse251/lecture6.pdfCSE 251 Dr. Charles B. Owen 2 Programming in C Triangle Area Computation a = p2 −p1 p2=(x2 y2) p3=(x3,y3) 3 2 3 1 c p p b

Function: DisplayResultvoid DisplayResult(double CTemp, double FTemp){  

printf("Original: %5.2f C\n", CTemp);printf("Equivalent: %5 2f F\n" FTemp);printf( Equivalent: %5.2f F\n , FTemp);

return;}

CSE 251 Dr. Charles B. OwenProgramming in C29

Page 30: Functions - Michigan State Universitycse251/lecture6.pdfCSE 251 Dr. Charles B. Owen 2 Programming in C Triangle Area Computation a = p2 −p1 p2=(x2 y2) p3=(x3,y3) 3 2 3 1 c p p b

Declarations (Prototypes)

double GetTemp( );           double CelsiusToFahrenheit( double );double CelsiusToFahrenheit( double );void Display( double, double );

• voidmeans “nothing”. If a function doesn’t return a gvalue, its return type is void

CSE 251 Dr. Charles B. OwenProgramming in C30

Page 31: Functions - Michigan State Universitycse251/lecture6.pdfCSE 251 Dr. Charles B. Owen 2 Programming in C Triangle Area Computation a = p2 −p1 p2=(x2 y2) p3=(x3,y3) 3 2 3 1 c p p b

Abstraction 1. Get Temperature2. Convert Temperature

int main(){doubleTempC // Temperature in degrees Celsius

p3. Display Temperature

TempC,                 // Temperature in degrees CelsiusTempF;                 // Temperature in degrees Fahrenheit

TempC = GetTemperature();( )TempF = CelsiusToFahrenheit(TempC);

DisplayResult(TempC, TempF); 

return 0; We are hiding details on how somethingreturn 0;} 

We are hiding details on how something is done in the function implementation.

CSE 251 Dr. Charles B. OwenProgramming in C31

Page 32: Functions - Michigan State Universitycse251/lecture6.pdfCSE 251 Dr. Charles B. Owen 2 Programming in C Triangle Area Computation a = p2 −p1 p2=(x2 y2) p3=(x3,y3) 3 2 3 1 c p p b

Another Way to Compute Factorial

Pseudocode for factorial(n)

if n == 0 thenresult = 1

else result = n * factorial(n – 1)result = n   factorial(n – 1)

After all, 5! = 5 * 4 * 3 * 2 * 1 = 5 * 4!

CSE 251 Dr. Charles B. OwenProgramming in C32

Page 33: Functions - Michigan State Universitycse251/lecture6.pdfCSE 251 Dr. Charles B. Owen 2 Programming in C Triangle Area Computation a = p2 −p1 p2=(x2 y2) p3=(x3,y3) 3 2 3 1 c p p b

Factorial function contains an invocation of itself.

Recursive Functionsinvocation of itself.

We call this a: recursive call.

int Factorial(int n){

if(n == 0)t 1return 1;

else return n * Factorial(n‐1);

}

Recursive functions must have a base case

}

This works much like proof by induction (if n == 0): why?proof by induction.

if n == 0 thenif n   0 thenresult = 1

else result = n * factorial(n 1)

CSE 251 Dr. Charles B. OwenProgramming in C33

result = n * factorial(n – 1)

Page 34: Functions - Michigan State Universitycse251/lecture6.pdfCSE 251 Dr. Charles B. Owen 2 Programming in C Triangle Area Computation a = p2 −p1 p2=(x2 y2) p3=(x3,y3) 3 2 3 1 c p p b

Infinite Recursion What if I omit the “base case”?

int Factorial(int n){

return n * Factorial(n‐1);}

This leads to infinite recursion!

}

Factorial(3)=

cbowen@ubuntu:~/cse251$ ./combi1Input n: 5Input k: 3Factorial(3)=

3 * Factorial(2) = 3 * 2 * Factorial(1) = 3 * 2 * 1 * Factorial(0) =

Input k: 3Segmentation fault

3   2   1   Factorial(0) 3 * 2 * 1 * 0 * Factorial(‐1) = … 

CSE 251 Dr. Charles B. OwenProgramming in C34

Page 35: Functions - Michigan State Universitycse251/lecture6.pdfCSE 251 Dr. Charles B. Owen 2 Programming in C Triangle Area Computation a = p2 −p1 p2=(x2 y2) p3=(x3,y3) 3 2 3 1 c p p b

Psuedocode and Function if n == 0 thenresult = 1

int Factorial(int n){

if(n == 0)t 1

else result = n * factorial(n – 1)Base Case

return 1;else 

return n * Factorial(n‐1);}}

Declaration:  int Factorial(int n);

Invocation: f = Factorial(7);Invocation:     f   Factorial(7);

Definition:     

int Factorial(int n){

if(n == 0)freturn 1;

else return n * Factorial(n‐1);

}

CSE 251 Dr. Charles B. OwenProgramming in C35 2