3. functions

40
Functions 1

Upload: innovatorinnovator

Post on 12-Jan-2016

215 views

Category:

Documents


1 download

DESCRIPTION

function

TRANSCRIPT

Page 1: 3. Functions

Functions

1

Page 2: 3. Functions

What is a Function?

� A function is a block of code that performs a particular task.

� A function can be called from the same or another function whenever required. Hence we can avoid rewriting the same code. It also improves the readability of the program. improves the readability of the program.

� Function may take some input in the form of parameters and sent out some output in the form of return value.

2

Page 3: 3. Functions

Example1: function without argument and return type

/* Using function :program to determine if an integer greater than 100 entered by the user is a prime number */

int num;

main(){num is declared as global variable so that it is accessible by all the functions.main(){

while(1){

printf("enter an integer greater than 100 ");

scanf("%d",&num);

if(num<100) continue;

printprime();

break;}}

it is accessible by all the functions.

primef1.c3

Page 4: 3. Functions

printprime()

{

int j,i,flag=1;

j=num/2;

for (i=2;i<=j;i++){

if(num%i==0){

flag=0;

printf("Not prime");

break;

}

}

if (flag) printf("Prime number");

}4

Page 5: 3. Functions

Return value

� Some compiler throws a warnings if function does

not return a integer value.

� A function must either return a value or must be

declared as void.declared as void.

5

Page 6: 3. Functions

Function declarationreturn_type function_name(argument-list)

Where argument-list is

Data-type var-name1, Data-type var-name2,… Data-type var-nameN

� If return_type is not specified it is assumed to be an int.

� argument-list can contain 0 one or more � argument-list can contain 0 one or more arguments.

� function_name must be unique. It should not clash with any variable name or other function name.

� Variables declared inside the function and the argument-list variables are local to the function. They cannot be accessed outside the function.

6

Page 7: 3. Functions

return

� The return statement is used to return a value

from a function.

� When return is encountered the control go back

to the calling function.

� Example:

• return (a);

• return (15);

• return 0;

• return;

Used with void. Does not return anything!

7

Page 8: 3. Functions

Prototyping

� Complier assumes that any C function would return a type int.

� Any function that returns types other than intmust inform the compiler by what is called prototyping.prototyping.

� Prototyping is declaring the function that needs to be called within the calling function.

� Note that declaration of a function is different from definition of a function.

8

Page 9: 3. Functions

Changing the prime number code

primef3.cint num;

int main(){

void pprime();

while(1){

printf("enter an integer greater than

100 ");

Declaring the called function in the

calling function since called function

returns void.

100 ");

scanf("%d",&num);

if(num<100) continue;

pprime();

break;

}

return 0}9

Page 10: 3. Functions

void pprime()

{

int j,i,flag=1;

j=num/2;

for (i=2;i<=j;i++){

if(num%i==0){

Defining the called function

flag=0;

printf("Not prime");

break;

}

}

if (flag) printf("Prime number");

return;

}optional 10

Page 11: 3. Functions

Function with parameters

� It is possible for the calling function to pass values into the called function through what is called parameters or arguments.

11

Page 12: 3. Functions

Example of function with parameters

/* program that has a function which calulates the gross salary given the basic salary*/

main(){main(){

double basic,gross;

double calculateGross(double basic);

printf("enter basic salary ");

scanf("%lf",&basic);

gross= calculateGross(basic);

printf("Gross=%lf",gross);

}

gross.c

12

Page 13: 3. Functions

double calculateGross(double basic){

double hra,ta,da, gross;

da=0.5 * basic;

hra=0.1 *basic;

if(basic<10000)

ta=1000;

else

if(basic>=10000 && basic<20000)if(basic>=10000 && basic<20000)

ta=2000;

else

ta=3000;

gross=basic+hra+ta+da;

return gross;

} 13

Page 14: 3. Functions

Without static variable� Suppose we attempt to write a code that prints

the number of times a function is called.main(){

void callMe();

callMe();

callMe();}

void callMe(){

count1.c

void callMe(){

int count;

count++;

printf("you called me %d times\n" , count);}

� When we execute the following code it prints garbage value for count because count is not initialized. 14

Page 15: 3. Functions

• If we initialize count to 0 then print “you called me 1 times” three times.

main(){

void callMe();

callMe(); callMe();

callMe();}

void callMe(){

int count=0;int count=0;

count++;

printf("you called me %d times\n" , count);}

• This is because the value of count gets initialized each time the function is called.

• What we want is a way in which count value can be retained.

15

Page 16: 3. Functions

static variable

� Solution to this is to declare the count variable

as static variable.

� Static variables are automatically initialized the � Static variables are automatically initialized the

first time to 0.

� It retains the value between the function calls

16

Page 17: 3. Functions

Count example corrected

main(){

void callMe();

callMe();

callMe();

callMe();

Prints:you called me 1 times

callMe();

}

void callMe(){

static int count;

count++;

printf("you called me %d times\n" , count);

}

you called me 2 times

you called me 3 times

17

Page 18: 3. Functions

Revisiting Storage class specifiers

� static local:

� scope: variables declared and accessed only inside block

� default:0

� Retains the value between function calls� Retains the value between function calls

� static keyword is specified with declaration

18

Page 19: 3. Functions

Call by value

void main(){

void f(int i,int j);

int i=0, j=0;

printf("Before calling f(): value of printf("Before calling f(): value of i=%d and value of j=%d\n", i,j);

f(i,j);

printf("After calling f(): value of i=%d and value of j=%d\n", i,j);

}19

Page 20: 3. Functions

void f(int i,int j){

printf("In f() before changing : value of i=%d

and value of j=%d\n", i,j);

i++;

j++;

printf("In f() after changing: value of i=%d

and value of j=%d\n", i,j);

}

Before calling f(): value of i=0 and value of j=0

In f() before changing : value of i=0 and value of j=0

In f() after changing: value of i=1 and value of j=1

After calling f(): value of i=0 and value of j=0

Result of execution

20

Page 21: 3. Functions

Observation

� What do you observe?

� The parameter values changed in the called function code are not reflected in the calling function.

� This is because the parameters are passed by � This is because the parameters are passed by value to the function.

� Both functions have their own copy of the variables. Only the values of the variables of the calling function get copied to the variables of the called function

21

Page 22: 3. Functions

1000

1001

1002

1003

1004

Addressmain()

i

j 0

0Call f(0,0)

f()

0

0

1

1i

j

MEMORY

1005f()

i

j

i++;

j++;

i

j 22

Page 23: 3. Functions

main()

i=0

j=0

Callsf()

1000

1001

i=0 2000

i=1

j=1

Value of i and j

in 1000 and

In memory

j=0 2001

i++;

j++;

in 1000 and

1001 remain

the same!

23

Page 24: 3. Functions

Call by reference

� What should be done so that the changed values of i and j are reflected in the calling function?

� There should be some way in which we pass the addresses of the variables of i and j from the calling function to the called function.the calling function to the called function.

� The called function should receive these variables in a way such that they point to values rather than just receiving the values.

24

Page 25: 3. Functions

Call by reference cont…

� &variable-name represents the address of the

variable.

� Address of a variable is of integer type.

� We need a special kind of variable that is

capable of holding an address and using which

we can retrieve the value stored in the address.

� Such a kind of variable is called a ‘Pointer’.

25

Page 26: 3. Functions

Introduction to pointers

� A pointer is a variable that holds an address of a

variable in memory and using this pointer we can

access the value stored in that location.

� Declaration:� Declaration:

• Data-type *variable_name;

� Data-type in the above syntax represents what

type of data the pointer points to.

� Example:

• double i=10;

26

Page 27: 3. Functions

Getting the address and value

� *variable-name returns the value stored in the

address that variable-name points to.

� variable-name returns the address value.� variable-name returns the address value.

� Example:

double i=10;

double *p=&i;

printf(“%lf”,*p);

printf(“%d”,p);

Prints 10

Prints the address

point.c27

Page 28: 3. Functions

Question ?

� It is important to specify the appropriate data-type

in the syntax if you want to use pointer arithmetic.

?

The data-type of a pointer variable is always integer.

Then what is the significance of specifying data-type

in the declaration syntax?

in the syntax if you want to use pointer arithmetic.

� You can use ++ and – operators on the pointer

which allows pointer to jump to next location.

Whether the jump has to be 1 byte , 2 bytes , 4

bytes, 8 bytes or 10 bytes is determined by the

data-type of the pointer.

More details on it in the pointers part

of the C story.28

Page 29: 3. Functions

Call by reference/* program : call by value demo */

void main(){

void f(int *i,int *j);

int i=0, j=0;

printf("Before calling f(): value of printf("Before calling f(): value of i=%d and value of j=%d\n", i,j);

f(&i,&j);

printf("After calling f(): value of i=%d and value of j=%d\n", i,j);

}29

Page 30: 3. Functions

void f(int *i,int *j)

{

printf("In f() before changing : value

of i=%d and value of j=%d\n", *i,*j);

*i++;

*j++;

(*i)++;

(*j)++;*j++;

printf("In f() after changing: value of

i=%d and value of j=%d\n", *i,*j);

}

(*j)++;

Do you see any problem with the code ?30

Page 31: 3. Functions

Recursion

� A function that calls itself is a recursive function.

� It is very important that a recursive function has an

exit point. Otherwise it will get into infinite loop.int i;

main(){int i;

main(){ main(){

f();}

int f(){

i++;

if(i>5) return ;

f();}

main(){

f();}

int f(){

f();

}

Without termination condition : infinite loop

Termination condition specified. Executes successfully.

31

Page 32: 3. Functions

Prime number using recursion

/* prime number using recursion */

int num,k;

main(){

printf("enter an integer ");

scanf("%d",&num);

/* do the checks on num before calling /* do the checks on num before calling the function */

k=prime(2);

if(k==0)

printf("not prime");

else

printf("prime");

} 32

Page 33: 3. Functions

int prime(int i){

if(num%i==0) return 0;

i++;

if(i>num/2) return 1;

elseelse

prime(i);

}

33

Page 34: 3. Functions

Flow

Assume num=9

prime(2) {if(num%i==0) return 0;���� 9%2!=0

i++;����2++���� 3

if(i>num/2) return 1;����3>(9/2) No!

else

����

1

Return value: 0

prime(i); ���� prime(3) }

{if(num%i==0) return 0;���� 9%3

i++;

if(i>num/2) return 1;

else

prime(i);}

Return value: 02 3

4

34

Page 35: 3. Functions

Fibonacci numbers

main(){

int f1=0,f2=1,f3,i;

printf("%d, %d,",

f1,f2);

for(i=0;i<8;i++)

{

main(){

void fibo(int f1, int f2);

int f1=0,f2=1,f3,i;

printf("%d, %d,", f1,f2);

fibo(f1,f2);

}

void fibo(int f1, int f2){

Non-recursive Recursive

{

f3=f1+f2;

f1=f2;

f2=f3;

printf("%d,", f2);

}

}

void fibo(int f1, int f2){

static int count;

int f3;

if(count>8) return;

f3=f1+f2;

f1=f2; f2=f3;

printf("%d,", f2);

count++;

fibo(f1,f2);}fib.cfibr.c

Termination condition

35

Page 36: 3. Functions

Use of recursion

� Recursive programs sometime seem rather difficult in

comparison to non-recursive ones.

� But in some cases it is actually easier to use recursion.

� For example in cases where you have a mathematical

formula based on iterative value of n.formula based on iterative value of n.

� For example- factorial value of n.

� Mathematical formula:

� FIB(N+1)=FIB(N)+F(N-1)

� fact(n)= n*fact(n-1) for all n<1

36

Page 37: 3. Functions

Recursive codemain(){

int num, res;

printf("enter a number");

scanf("%d",&num);

res=fact(num);

printf("%d",res);

}}

int fact(int n){

int f;

if(n==1) return 1;

f=n*fact(n-1);

return f;

}37

Page 38: 3. Functions

Flownum=3

fact(3)

{int f;

if(n==1) return 1; ���� n=3

f=n*fact(n-1);���� 3*fact(2) Return 2

Return 6

return f;}{int f;

if(n==1) return 1; ���� n=2

f=n*fact(n-1);���� 2*fact(1)

return f;}{

int f;

if(n==1) return 1; ���� n=1

f=n*fact(n-1);

return f;}

Return 1

38

Page 39: 3. Functions

Word of caution!

• Recursive code may be difficult to understand

and debug. Hence it should be used only in

places where it makes the overall program places where it makes the overall program

simpler.

•Recursive code adds to overhead of multiple

function calls.

39

Page 40: 3. Functions

?Did we come across any of the predefined functions in C so far?

scanf

Did we completely understand functions?

scanf

printf

How many arguments does printf take?

40