Top Banner
CS 161 Introduction to Programming and Problem Solving Chapter 24 C Functions Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from ECE 103 material by prof. Phillip Wong @ PSU
26

CS 161 Introduction to Programming and Problem Solving Chapter 24 C Functions Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from.

Jan 17, 2016

Download

Documents

Suzanna Cannon
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: CS 161 Introduction to Programming and Problem Solving Chapter 24 C Functions Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from.

CS 161Introduction to Programming

and Problem Solving

Chapter 24C Functions

Herbert G. Mayer, PSUStatus 9/8/2014

Initial content copied verbatim fromECE 103 material by prof. Phillip Wong @ PSU

Page 2: CS 161 Introduction to Programming and Problem Solving Chapter 24 C Functions Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from.

Syllabus Introduction Function Definition Parameter List Function Body Function Declaration Examples Recursion

Page 3: CS 161 Introduction to Programming and Problem Solving Chapter 24 C Functions Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from.

3

Introduction A program can be divided into multiple parts Logical partitions are named: modules Physical partitions are named: C functions Each function has a name; when listed in a C

program, the respective function is “called” or “invoked” to do its logical task at that code location

Why are functions useful? Organization – divides tasks into subtasks Encapsulation – hides design and implementation details

from view of the rest of the program Simplification – reduces unnecessary code repetition Modularity – creates reusable code libraries

Page 4: CS 161 Introduction to Programming and Problem Solving Chapter 24 C Functions Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from.

4

Arguments, AKA actual parameters, contain data that the caller passes to the function Arguments can be literal constants, variables, data

structures, or expressions Some functions require multiple arguments, while

others may need no arguments at all The Return Value returns data back to the caller

A function can return a single value or no value at all, in which case it is a void function

C FunctionArgumentsReturnValue

Page 5: CS 161 Introduction to Programming and Problem Solving Chapter 24 C Functions Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from.

5

Example:

Sample function calls:

fun1(); // no input arg, no ret valfun2( n ); // 1 input arg, AKA 1 actualfun3( 1.25, "xm” ); // 2 input args: 2 actuals

R = rand(); /* no arg, 1 return value */y = sin( x ); /* 1 arg, 1 return value */w = pow( 2.5, 3 ); /* 2 args, 1 return value */

/* 5 input args, 1 return value */val = myfun( "PSU", 'x', 3.5, ivar, 2*cos( A ) );

Page 6: CS 161 Introduction to Programming and Problem Solving Chapter 24 C Functions Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from.

6

Function Definition

return_type function_name ( parameter_list ){ // function_name

local variable declarationscode statements

} //end function_name

Function definition consists of: header – defines required function inputs/outputs body – defines the function code Body includes return operation, even default fall-thru

Function names follow variable naming rules

Function body{between braces}

Header

Page 7: CS 161 Introduction to Programming and Problem Solving Chapter 24 C Functions Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from.

7

Parameter List:

The formal parameter list defines expected data to be passed to function Formal Parameters are local function variables,

generally initialized at place of call via actuals Names and data types of parameter are declared Multiple parameters are separated by commas During a call, the actual parameters are bound to the

formal parameters If no parameters are needed, the list is declared as

type void

Page 8: CS 161 Introduction to Programming and Problem Solving Chapter 24 C Functions Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from.

8

Are arguments (actuals) and parameters (formals) the same?

→ No. Arguments are the values passed to the function. Parameters are the function’s internal variables that hold copies of the passed values.

Example:int x = 3, y = 5, k;

char c = '#';

k = fun( x, y, 42, c ); . . .int fun( int x, int y, int z, char c ){ . . . }

The contents of variables x, y, c, along with the constant 42, are passed to the function. These are called arguments.

These variables x, y, z, c receive the values passed to the function. They are called parameters.

Page 9: CS 161 Introduction to Programming and Problem Solving Chapter 24 C Functions Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from.

9

Must an argument variable have the same name as its corresponding parameter variable?→ No. They independent of one another

Example:int a = 3, b = 5, k;char m = '#';

k = fun( a, b, 42, m );. . .

int fun( int x, int y, int z, char c ){ . . . }

Function call

Function definition

'#'4253

Page 10: CS 161 Introduction to Programming and Problem Solving Chapter 24 C Functions Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from.

10

Example:/* Function definition */void display( int xval, char ch, double * ptr ){ // display

printf( "%d %c %p\n", xval, ch, ptr );} //end display

int xval = 3, cat = 3;char ch = 'T', z = 'T';double * ptr = & xval, * q = & xval; // careful!!!

// Some function calls:display( 3, 'T', & xval ); // careful!!!display( xval, ch, ptr );display( cat, z, q );/* In each case, the value of the argument * is stored in the corresponding parameter

*/

Page 11: CS 161 Introduction to Programming and Problem Solving Chapter 24 C Functions Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from.

11

If possible, an argument's type will be promoted or demoted to match its parameter's type

Example:/* Function definition */void fun( int u, double v ){ . . . }

int x = 2;double y = 3.1415;

/* Some function calls */fun( x, y ); /* u contains 2, v contains 3.1415 */fun( y, x ); /* u contains 3, v contains 2.0 */

Incompatible arguments can cause programs to fail at runtime! Be very carful!!

Page 12: CS 161 Introduction to Programming and Problem Solving Chapter 24 C Functions Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from.

12

Return type:

Return type can be: Variant of char, int, float, double, struct Pointer (i.e., memory address) void (if no value is to be returned)

If the function returns a value, then a return statement is needed in the function body.Example:double Compute_Vx (double V, double angle){

return V * sin( angle );}

Page 13: CS 161 Introduction to Programming and Problem Solving Chapter 24 C Functions Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from.

13

Function Body Function body contains:

Local variable declarations Local prototype declarations Code that defines what the function does Including code to specify return value

Braces { } mark the beginning and end of the function body

There is no semicolon after the final brace In C, a function definition cannot be nested inside

another function definition! Note: gcc extension!

Page 14: CS 161 Introduction to Programming and Problem Solving Chapter 24 C Functions Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from.

14

Example:/* Program #1 Compute areas of triangles - without separate function */#include <stdio.h>

int main( void ){ // main

float b, h; /* base and height */float A1, A2; /* area */

A1 = ( 3.0 * 1.5 ) / 2.0;printf( "Area1 = %f\n", A1 );

b = 2.5; h = 15.4; A2 = ( b * h ) / 2.0;printf( "Area2 = %f\n", A2 );

b = 0.33; h = 5.7;printf( "Area3 = %f\n", ( b * h ) / 2.0 );

return 0;} //end main

Page 15: CS 161 Introduction to Programming and Problem Solving Chapter 24 C Functions Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from.

15

Example:/* Program #2 Compute areas of triangles – with function */

#include <stdio.h>

float triangle_area( float base, float height ){ // triangle_area

return ( base * height ) / 2.0f;} //end triangle_area

int main( void ){ // main

float b, h; /* base and height */float A1, A2; /* area */

A1 = triangle_area( 3.0f, 1.5f );printf( "Area1 = %f\n", A1);

b = 2.5f; h = 15.4f; A2 = triangle_area( b, h );printf( "Area2 = %f\n", A2);

b = 0.33f; h = 5.7f;printf( "Area3 = %f\n", triangle_area( b, h ) );

return 0;} //end main

Page 16: CS 161 Introduction to Programming and Problem Solving Chapter 24 C Functions Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from.

16

Declaring a Function

Functions must be defined before they are first used

Does this imply that functions must be placed in the source file in a specific order? It depends

For functions, C has two approaches to meet the "define-before-use" rule: Define functions in order within the source file Use function prototypes

Page 17: CS 161 Introduction to Programming and Problem Solving Chapter 24 C Functions Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from.

17

Approach #1: Ordered Definitions

Within the source file, function definitions that are used first are placed before functions that call them

Example:Suppose A, B, C, D are functions. B calls C,D calls C, and A calls D:

CBDA

Top of source file

Page 18: CS 161 Introduction to Programming and Problem Solving Chapter 24 C Functions Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from.

18

Example:void fun1( void ){ // fun1

int x;. . .x = 3;

} //end fun1

void fun2( void ){ // fun2

int x;. . .x = 5;fun1();

} //end fun2

int main( void ){ // main

int x;x = 7;fun1();fun2();return 0;

} //end main

fun1 defined 1st since both fun2 and main call it.

fun2 defined 2nd since main calls it (but not fun1).

main defined last

Page 19: CS 161 Introduction to Programming and Problem Solving Chapter 24 C Functions Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from.

19

Approach #2: Prototypes A function can be declared before being defined A function declaration is just the function header by

itself followed by a semicolon (no body) These declarations are called prototypes Prototypes are usually placed at the top of the

source file before the actual function definitions Prototypes allow the compiler to determine the basic

input/output characteristics of functions without needing to know the internal details

By the end of the compilations, bodies for the prototypes must be available

Page 20: CS 161 Introduction to Programming and Problem Solving Chapter 24 C Functions Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from.

20

Example 1, with formal parameter names:#include <stdio.h>/* Function prototypes */void display( char ch, int xval );float calculate( int x );

int main( void ){ // main

display( 'G', 8 );return 0;

} //end main

/* Function definitions */void display( char ch, int xval ){ // display

printf( "%c %d %f\n", ch, xval, calculate( xval ) );} //end display

float calculate( int x ){ // calculate

return x*x / 3.0;} //end calculate

Once the prototypes are declared, the order in which the functions are defined does not matter

NOTE:The main() function does not need to be declared.

Page 21: CS 161 Introduction to Programming and Problem Solving Chapter 24 C Functions Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from.

21

Example 2 without formal parameter names:#include <stdio.h>/* Function prototypes */void display( char, int );float calculate( int );

int main( void ){ // main

display( 'G', 8 );return 0;

} //end main

/* Function definitions */void display( char ch, int xval ){ // display

printf( "%c %d %f\n", ch, xval, calculate( xval ) );} //end display

float calculate( int x ){ // calculate

return x*x / 3.0;} //end calculate

Page 22: CS 161 Introduction to Programming and Problem Solving Chapter 24 C Functions Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from.

22

Example 3 function min( int, int ) with 3-4 args?#include <stdio.h>

int min( int arg1, int arg2 ){ // min

return arg1 < arg2 ? arg1 : arg2;} //end min

int main( void ){ // main

printf( “min of 2, -3 = %d\n”, min( 2, -3 ) );printf( “min of 2, 12, 3 = %d\n”, min( 2, min( 12, 3 ) ) );printf( “min of -9, 2, 12, 3 = %d\n”, min( min( -9, 2 ), min( 12, 3 ) ) );return 0;

} //end main

Page 23: CS 161 Introduction to Programming and Problem Solving Chapter 24 C Functions Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from.

23

No parameters Single parameter Multiple parameters (e.g., 2)

No return value

Declarationvoid fun (void);

Declarationvoid fun (dtype a);

Declarationvoid fun (dtype a, dtype b);

Definitionvoid fun (void){ /* return not needed */}

Definitionvoid fun (dtype a){ /* return not needed */}

Definitionvoid fun (dtype a, dtype b){ /* return not needed */}

Callfun();

Callfun(x);

Callfun(x, y);

Single return value

Declarationdtype fun (void);

Declarationdtype fun (dtype a);

Declarationdtype fun (dtype a, dtype b);

Definitiondtype fun (void){ return expr;}

Definitiondtype fun (dtype a){ return expr;}

Definitiondtype fun (dtype a, dtype b){ return expr;}

Callz = fun();

Callz = fun(x);

Callz = fun(x, y);

Page 24: CS 161 Introduction to Programming and Problem Solving Chapter 24 C Functions Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from.

24

Recursive Functions

A function f() may call itself! Either directly, i.e. from inside its own body of f() Or indirectly, from inside another function g(), which

was in turn called by f() The former is referred to as “directly recursive calls” The latter a “indirect recursive calls” Recursion is a powerful programming tool, so strong,

it can replace almost all other tools; though that is not a recommended approach

Page 25: CS 161 Introduction to Programming and Problem Solving Chapter 24 C Functions Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from.

25

Recursive Function Definition

A function f() is recursive, if it is partly defined by simpler versions of f() itself

The partly is important, providing for a base case, a case where the result is known and no further calls are made at all

The simpler version is also important, else there would be no recursion at all, but instead infinite regress instead; that is as bad as an infinite loop

Let’s see an example:

Page 26: CS 161 Introduction to Programming and Problem Solving Chapter 24 C Functions Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from.

26

Simple Recursive Function: fact()#include <stdio.h>

// compute the unsigned factorial of an unsigned argumentunsigned fact( unsigned arg ){ // fact

if ( 0 == arg ) {return 1;

}else{return fact( arg – 1 ) * arg;

} //end if} //end fact

int main( void ){ // main

int i;for ( i = 0; i < 10; i++ ) {

printf( “fact(%d) = %d\n”, i, fact( i ) );} //end for

} //end main