Lec8 Function

56
1 Modular Programming In C Language Functions

description

computation c

Transcript of Lec8 Function

1

Modular Programming In C Language

Functions

2

Topics

• Functions• Parameters• Return values• Prototype• Scope• Recursion• Standard C Library

3

User-Defined Functions• Create your own functions, similar to printf() or

sqrt()• Function call analogy:

– Boss asks worker to complete task• Worker gets information, does task, returns result• Information hiding: boss does not know details

Benefits of functions

• Divide and conquer• Construct a program from smaller Manageable pieces or

components– These smaller pieces are called modules

• Each piece more manageable than the original program

• Software reusability• Use existing functions as building blocks for new programs• Abstraction - hide internal details (library functions)

• Avoid code repetition

4

5

Writing User-defined Functions

• Need to specify:– the name of the function– its parameters– what it returns– block of statements to be carried out when the

function is called

• The block of statements is called the “function body”

6

#include <stdio.h>

/** Print a simple greeting.*/

void sayHello ( void ){printf(“Hello World!\n”);

}

/** Call a function which* prints a simple greeting.*/

int main(void){sayHello();return 0;

}

Example: hello1.c

7

Example: hello1.c

Function definition

Function call

#include <stdio.h>

/** Print a simple greeting.*/

void sayHello ( void ){printf(“Hello World!\n”);

}

/** Call a function which * prints a simple greeting.*/

int main(void){sayHello();return 0;

}

8

Example: hello1.c

Function name

Function body

#include <stdio.h>

/** Print a simple greeting.*/

void sayHello ( void ){printf(“Hello World!\n”);

}

/** Call a function which* prints a simple greeting.*/

int main(void){sayHello();return 0;

}

9

Example: hello1.c

Return type

Formal Parameter List

#include <stdio.h>

/** Print a simple greeting.*/

void sayHello ( void ){printf(“Hello World!\n”);

}

/** Call a function which * prints a simple greeting.*/

int main(void){ sayHello();return 0;

}

10

Parameters

• Information passed to a function• “Formal” parameters are local variables

declared in the function declaration.• “Actual” parameters are values passed to

the function when it is called.

11

/* Print two numbers in order. */

void badSort ( int a, int b ){int temp;

if ( a > b ){printf("%d %d\n", b, a);

}else{printf("%d %d\n", a, b);

}}

Example: badsort.c

Parameters (aka Arguments)

12

Example: badsort.c/* Print two numbers in order. */

void badSort ( int a, int b ){int temp;

if ( a > b ){printf("%d %d\n", b, a);

}else{printf("%d %d\n", a, b);

}}

13

int main(void){int x = 3, y = 5;

badSort ( 10, 9 );badSort ( y, x+4 );return 0;

}

Example: badsort.c

/* Print two numbers in order. */

void badSort ( int a, int b ){int temp;

if ( a > b ){printf("%d %d\n", b, a);

}else{printf("%d %d\n", a, b);

}}

Formal parameters

Actual parameters

14

Parameters (cont.)

• Parameters are passed by copying the value of the actual parameters to the formal parameters.

• Changes to formal parameters do not affect the value of the actual parameters.

15

int main(void){int a = 3, b = 5;

printf("%d %d\n",a,b); badSwap ( a, b );printf("%d %d\n",a,b);

return 0;}

Example: badswap.c

/* Swap the values of two variables. */

void badSwap ( int a, int b ){int temp;

temp = a;a = b;b = temp;

printf("%d %d\n", a, b);}

16

Example: badswap.c

Output: 3 5

int main(void){int a = 3, b = 5;

printf("%d %d\n",a,b); badSwap ( a, b );printf("%d %d\n",a,b);

return 0;}

/* Swap the values of two variables. */

void badSwap ( int a, int b ){int temp;

temp = a;a = b;b = temp;

printf("%d %d\n", a, b);}

17

Example: badswap.c

Output: 3 55 3

int main(void){int a = 3, b = 5;

printf("%d %d\n",a,b); badSwap ( a, b );printf("%d %d\n",a,b);

return 0;}

/* Swap the values of two variables. */

void badSwap ( int a, int b ){int temp;

temp = a;a = b;b = temp;

printf("%d %d\n", a, b);}

18

Example: badswap.c

Output: 3 55 33 5

int main(void){int a = 3, b = 5;

printf("%d %d\n",a,b); badSwap ( a, b );printf("%d %d\n",a,b);

return 0;}

/* Swap the values of two variables. */

void badSwap ( int a, int b ){int temp;

temp = a;a = b;b = temp;

printf("%d %d\n", a, b);}

19

Example: badswap.c

Calling function’s environment:

a: 3b: 5

Called function’s environment:

a: 5b: 3

int main(void){int a = 3, b = 5;

printf("%d %d\n",a,b); badSwap ( a, b );printf("%d %d\n",a,b);

return 0;}

/* Swap the values of two variables. */

void badSwap ( int a, int b ){int temp;

temp = a;a = b;b = temp;

printf("%d %d\n", a, b);}

20

Parameters (cont.)

• If a function does not take parameters, declare its formal argument list void.

void sayHello ( void ){printf(“Hello World!\n”);

}

sayHello();Function call:

Declaration:

21

Return Values

• Values are returned by copying a value specified after the return keyword

22

/* Returns the larger of two numbers. */

int max (int a, int b){int result;

if (a > b){result = a;

}else{result = b;

}

return result;}

Example: max.c

Return type

23

/* Returns the larger of two numbers. */

int max (int a, int b){int result;

if (a > b){result = a;

}else{result = b;

}

return result;}

Example: max.c

For example:

The value of the expression

max(7,5)

is the integer 7.

24

/* Returns the larger of two numbers. */

intmax (int a, int b){int result;

if (a > b){result = a;

}else{result = b;

}

return result;}

Example: max.c

This style okay.

25

Return Values (cont.)

• If a function does not return a value, declare its return type void.

void sayHello ( void ){printf(“Hello World!\n”);

}

sayHello();Function call:

Declaration:

26

Prototyping of Functions

• Must declare functions before use (like variables)

• Declaration is called a “prototype”• Specifies the name, parameters and return

type of the function, but not the code

27

#include <stdio.h>

int isNegative (int);

int main (void){

int number;

printf ("Enter an integer: ");scanf ("%d",&number);

if (isNegative(number)){

printf("Negative\n");}else{

printf("Positive\n");}

return 0;}

Example: isNegative.c

intisNegative ( int n ){

int result;if ( n<0 ){

result=1;}else {

result = 0;}return result;

}

28

#include <stdio.h>

int isNegative (int);

int main (void){

int number;

printf ("Enter an integer: ");scanf ("%d",&number);

if (isNegative(number)){

printf("Negative\n");}else{

printf("Positive\n");}

return 0;}

Example: isNegative.c

intisNegative ( int n ){

int result;if ( n<0 ){

result=1;}else {

result = 0;}return result;

}

Function Prototype

29

#include <stdio.h>

int isNegative (int);

int main (void){

int number;

printf ("Enter an integer: ");scanf ("%d",&number);

if (isNegative(number)){

printf("Negative\n");}else{

printf("Positive\n");}

return 0;}

Example: isNegative.c

intisNegative ( int n ){

int result;if ( n<0 ){

result=1;}else {

result = 0;}return result;

}

Function Definition

30

#include <stdio.h>

int isNegative (int);

int main (void){

int number;

printf ("Enter an integer: ");scanf ("%d",&number);

if (isNegative(number)){

printf("Negative\n");}else{

printf("Positive\n");}

return 0;}

Example: isNegative.c

intisNegative ( int n ){

int result;if ( n<0 ){

result=1;}else {

result = 0;}return result;

}

Function Call (Must be after prototype, but

can be before definition)

31

#include <stdio.h>

int isNegative (int);

int main (void){

int number;

printf ("Enter an integer: ");scanf ("%d",&number);

if (isNegative(number)){

printf("Negative\n");}else{

printf("Positive\n");}

return 0;}

Example: isNegative.c

intisNegative ( int n ){

int result;if ( n<0 ){

result=1;}else {

result = 0;}return result;

}

Header files (filename.h) contain function prototypes and global

variable declarations

32

#include <stdio.h>

int isNegative (int);

int main (void){

int number;

printf ("Enter an integer: ");scanf ("%d",&number);

if (isNegative(number)){

printf("Negative\n");}else{

printf("Positive\n");}

return 0;}

Example: isNegative.c

intisNegative ( int n ){

int result;if ( n<0 ){

result=1;}else {

result = 0;}return result;

}

stdio.h contains function prototypes for printf(), scanf(), and

other I/O functions

33

Header files

• You can make your own header files with prototypes of frequently used functions:#include "myFunctions.h"

• Put the functions in a corresponding C file, and include those too:#include "myFunctions.c"

34

#include <stdio.h>#include "myFunctions.h"#include "myFunctions.c"

int main (void){

int number;

printf ("Enter an integer: ");scanf ("%d",&number);

if (isNegative(number)){

printf("Negative\n");}else{

printf("Positive\n");}

return 0;}

Example: isNegative.c

Note:• " " around file name for user-defined files• < > for standard system files

isNegative() is declared in myFunctions.h and defined in myFunctions.c, not in this file!

35

Example: myFunctions.c

intisNegative ( int n ){

int result;if ( n<0 ){

result=1;}else {

result = 0;}return result;

}

Example: myFunctions.h

int isNegative ( int );

36

Scope

Where can you use a variable which is declared in a function?

• In that function only• Not in a calling function• Not in a called function

37

Scope: Local Variables

• Formal parameters: only accessible whilst function executing

• Variables declared in a function body: only accessible whilst function executing

• In fact, this is true of every block in a program

38

#include <stdio.h>

intisNegative ( int n ){

int result;if (number<0){

result=1;}else {

result = 0;}return result;

}

Example: isNegative.c

int main (void){

int number;

printf ("Enter an integer: ");scanf ("%d",&number);

if (isNegative(number)){

printf("Negative\n");}else{

printf("Positive\n");}

return 0;}

39

#include <stdio.h>

intisNegative ( int n ){

int result;if (number<0){

result=1;}else {

result = 0;}return result;

}

Example: isNegative.c

int main (void){

int number;

printf ("Enter an integer: ");scanf ("%d",&number);

if (isNegative(number)){

printf("Negative\n");}else{

printf("Positive\n");}

return 0;}

ERROR! Number is local to the main function, not accessible

here

40

#include <stdio.h>

intisNegative ( int n ){

int result;if ( n<0 ){

result=1;}else {

result = 0;}return result;

}

Example: isNegative.c

int main (void){

int number;

printf ("Enter an integer: ");scanf ("%d",&number);

if (isNegative(number)){

printf("Negative\n");}else{

printf("Positive\n");}

return 0;}

Use the parameter n which is local to the functionisNegative()

41

#include <stdio.h>

intisNegative ( int n ){

int result;if ( n<0 ){

result=1;}else {

result = 0;}return result;

}

Example: isNegative.c

int main (void){

int number;

printf ("Enter an integer: ");scanf ("%d",&number);

if (isNegative(number)){

printf("Negative\n");}else{

printf("Positive\n");}

return 0;}

number is the actual parameter

n is the formalparameter

42

#include <stdio.h>

intisNegative ( int n ){

int result;if ( n<0 ){

result=1;}else {

result = 0;}return result;

}

Example: isNegative.c

int main (void){

int number;

printf ("Enter an integer: ");scanf ("%d",&number);

if (isNegative(number)){

printf("Negative\n");}else{

printf("Positive\n");}

return 0;}

result & n: local to isNegative()number: local to main()

43

#include <stdio.h>

int number;

intisNegative ( void ){

int result;if ( number <0 ){

result=1;}else {

result = 0;}return result;

}

Example: isNegativeGlobal.c

int main (void){

printf ("Enter an integer: ");scanf ("%d",&number);

if (isNegative()){

printf("Negative\n");}else{

printf("Positive\n");}

return 0;}

44

#include <stdio.h>

int number;

intisNegative ( void ){

int result;if ( number <0 ){

result=1;}else {

result = 0;}return result;

}

Example: isNegativeGlobal.c

int main (void){

printf ("Enter an integer: ");scanf ("%d",&number);

if (isNegative()){

printf("Negative\n");}else{

printf("Positive\n");}

return 0;}

number is now GLOBAL -declared outside any function,

accessible in all functions (after the declaration)

45

Scope: Global Variables

• Global variables are accessible in any function after their declaration to the end of that source file

• They're useful, but risky – if any and every function can modify them, it

can be difficult to keep track of their value

• Better to use local variables and parameter passing if possible

Static Variables

• static: local variables defined in functions.– Keep value after function ends– Only known in their own function

46

47

Scope: Functions

• Functions are also accessible in any function after their declaration to the end of that source file

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;

Example Using Recursion: The Fibonacci Series

• Fibonacci series: 0, 1, 1, 2, 3, 5, 8...– Each number is the sum of the previous two – Can be solved recursively:

• fib( n ) = fib( n - 1 ) + fib( n – 2 )– Code for the fibaonacci function

long fibonacci( long n ){if (n == 0 || n == 1) // base case

return n;else

return fibonacci( n - 1) +fibonacci( n – 2 );

}

Example Using Recursion: The Fibonacci Series

• Set of recursive calls to function fibonaccif( 3 )

f( 1 )f( 2 )

f( 1 ) f( 0 ) return 1

return 1 return 0

return +

+return

Intrative powInt Function

//powInt function iterative versiondouble powInt(double y,int x){

int i; // local to powIntdouble pow=1; // local to powIntfor(i =1;i<=n;i++)

pow *=y;return pow;

}

recursive powInt Function

//powInt function recursive versiondouble powInt(double y,int x){

if (x == 1)return y

else return y*powInt(y,x-1);

}

54

C Standard Library Function math.h

FunctionName

MathName Value Example

abs(x) absolute value |x| abs(-1) returns 1

sqrt(x) square root x0.5 sqrt(2.0) returns 1.414…

exp(x) exponential ex exp(1.0) returns 2.718…

log(x) natural logarithm ln x log(2.718…) returns 1.0

log10(x) common logarithm log x log10(100.0) returns 2.0sin(x) sine sin x sin(3.14…) returns 0.0

cos(x) cosine cos x cos(3.14…) returns -1.0

tan(x) tangent tan x tan(3.14…) returns 0.0

ceil(x) ceiling + x + ceil(2.5) returns 3.0

floor(x) floor + x + floor(2.5) returns 2.0

C Standard Library Function ctype.h

55

Prototype Function description

int toupper( int c ); If c is a lowercase letter, toupper returns c as an uppercase letter. Otherwise, toupper returns the argument unchanged.

int isspace( int c ); Returns a true value if c is a white-space character—newline ('\n'), space (' '), form feed ('\f'), carriage return ('\r'), horizontal tab ('\t') or vertical tab ('\v')—and 0 otherwise.

int iscntrl( int c ); Returns a true value if c is a control character and 0 otherwise.

int ispunct( int c ); Returns a true value if c is a printing character other than a space, a digit, or a letter and returns 0 otherwise.

int isprint( int c ); Returns a true value if c is a printing character including a space (' ') and returns 0 otherwise.

int isgraph( int c ); Returns a true value if c is a printing character other than a space (' ') and returns 0 otherwise.

C Standard Library Function stdlib.h

• atoi (string_var): – convert string variable and return an integer

• atof (string_var): – convert string variable and return a float

• atol(string_var): – convert string variable and return a long int

• strtod(string_var, endstring): – convert string variable and return a double and stores the

rest non-double in endstring• strtol(string_var, endstring,0):

– convert string variable and return a long int and stores the rest non-long int in endstring

• strtoul(string_var, endstring,0): – convert string variable and return an unsigned long and

stores the rest non-long int in endstring