Function lecture

Post on 06-May-2015

490 views 0 download

description

Function is an important chapter in programming language C. this lecture slides are prepared considering BTech 1st year student in India.

transcript

A Lecture

on Function in C

Prepared by: AJAY KUMAR Assistant Professor Department of CSE DIT University, Dehradun

Introduction to Function in C

• Rely on person for so many other things

Eg. call a mechanic to fix up your bike

hire a gardener to mow your lawn

rely on a store to supply you groceries every month

• Similarly a computer program cannot handle all the tasks by itself.

• So it requests other program —called ‘functions’ in C—to get its tasks done.

2 visit us: http://sites.google.com/site/kumarajay7th/

Modular Programming (Top-Down Programming)

• Large program is broken into segments i.e.number of smaller and simpler tasks. • All individual segment is known as “module”.

Eg. In a mobile phone, contact list SMS calculator games so on…

Module

3 visit us:http://sites.google.com/site/kumarajay7th/

Advantage of Modular Programming

• Codes and variables are isolated from other program

• Easy to debug or trace the errors

• Reuse the same code in other program also

• Less effort to write a new code for similar task

eg. printf(), scanf(), clrscr(),sqrt()

4 visit us: http://sites.google.com/site/kumarajay7th/

Function

• A function is a self-contained block of statements that perform a coherent task of some kind.

• A function that calls or activates the function and the function itself.

F U N C T I O N

SYSTEM-DEFINED FUNCTION Or PRE-DEFINED function

Or Library function Or Built-in Function

User-Defined Function

5 visit us: http://sites.google.com/site/kumarajay7th/

Basic structure of function

Return_type function_name (arguments_list) { set of statements (or function body) }

6 visit us: http://sites.google.com/site/kumarajay7th/

Function (contd…)

• Built-in Function

Eg. Sqrt(),pow(),printf(),scanf()

• User-defined Function’s components

– Return type

– Function name

– Function argument list

– Function’s body= set of statements

7 visit us:http://sites.google.com/site/kumarajay7th/

Function categories on the basis of argument_list and return_type

• Function with no arguments and no return values

• Function with arguments and no return values

• Function with arguments and return values

• Function with no arguments and return values

8 visit us:http://sites.google.com/site/kumarajay7th/

First Program of Function #include<stdio.h> #include<conio.h> void main() { clrscr(); printf(“\n hello ”); message(); printf(“\n everyone”); getch(); } // function start message() { printf(“\n good morning”); }

Output: Hello Good morning everyone

1

2

3

9 visit us: http://sites.google.com/site/kumarajay7th/

First program of Function

#include<stdio.h> #include<conio.h> void main() { clrscr(); printf(“\n hello ”); message(); printf(“\n everyone”); getch(); } // function start message() { printf(“\n good morning”); }

Header File

Main function (Calling function)

body of statement in main function

Comments

User-defined function name (Called function)

Body of statement in user-defined function

10 visit us: http://sites.google.com/site/kumarajay7th/

Program example void main( ) { printf ( "\ni am in main function" ) ; italy( ) ; printf(“\n i am in middle of main”); brazil( ) ; printf(“\n i am back to main”); getch(); } italy() { printf(“\n Hi how are you?”); } brazil() { printf(“\n Hmmm, not bad!”); }

Output: ?

Output:

I am in main function Hi how are you? I am in middle of main Hmmm, not bad I am back to main

11 visit us: http://sites.google.com/site/kumarajay7th/

Why use function?

• Writing functions avoids rewriting the same code over and over.

• Separating the code into modular functions makes the program easier to design and understand.

12 visit us: http://sites.google.com/site/kumarajay7th/

Function categories on the basis of argument_list and return_type

• Function with no arguments and no return values

• Function with arguments and no return values

• Function with arguments and return values

• Function with no arguments and return values

13 visit us: http://sites.google.com/site/kumarajay7th/

Function with no arguments and no return values

#include<stdio.h> #include<conio.h> void my_sms(void); void main() { printf(“\n send me a message”); my_sms(); my_sms(); } void my_sms() { print(“\n plz rd my msg.”); }

output: send me a message plz rd my msg plz rd my msg

Function prototype declaration

14 visit us: http://sites.google.com/site/kumarajay7th/

Function with arguments and no return values

#include<stdio.h> void factorial(int); void main() { int n; printf(“\n enter a no.”); scanf(“%d”, &n); factorial(n); getch(); } void factorial(int m) { int i,f=1; for(i=1;i<=m;i++) f=f*i; printf(“\n factorial of %d is %d”, m,f); }

Output: Enter a no. 5 Factorial of 5 is 120

15 visit us: http://sites.google.com/site/kumarajay7th/

Function with arguments and return values

#include<stdio.h> int compute(int,int); void main() { int n1=100,n2=500,ans; ans=compute(n1,n2); printf(“\n largest no=%d”,ans); getch(); } int compute(int x,int y) { if(x>y) return x; else return y;

#include<stdio.h> float add (int,int); void main() { float n1,n2,ans; printf(“\n enter 2 no.”); scanf(“%f%f”,&n1,&n2); ans=add(n1,n2); printf(“\n sum=%f”,ans); getch(); } float add(int a,int b) { float result; result=a+b; return result; }

? ?

16 visit us: http://sites.google.com/site/kumarajay7th/

Function with No arguments and return values

#include<stdio.h> #include<conio.h> int p(); void main() { int my_p; clrscr(); my_p=p(); printf("\n power = %d", my_p); getch(); }

int p() { int i,power=1,n; printf("\n enter value for power:");

scanf("%d",&n); for(i=1;i<=n;i++) power=power*n; return power; } Output: enter value for power: 5

Power= 3125 55= 5 x 5 x 5 x 5 x 5=3125

17 visit us: http://sites.google.com/site/kumarajay7th/

Excercise

18

Exercise:

void main(){ int i = 10, j = 20 ; printf ( "%d %d %d ", i, j ) ; printf ( "%d", i, j ) ; }

void main() { int a = 1 ; printf ( "%d %d %d", a,++a,a++ ) ; }

Output: 3 3 1

Output; 10 20 860 10

Garbage value

visit us: http://sites.google.com/site/kumarajay7th/

assignment

• WAP to find the factorial of a number using function with arguments and return value

• Wap to find the cube of a number using function with argument but no return value

• Write a c function which returns the biggest of 3 numbers.

• Do the exercise from Let-Us-C

19 visit us: http://sites.google.com/site/kumarajay7th/

Function Prototype

Declaring a function is function prototype which provides the compiler with a description that will be defined at a later point in the program.

Syntax:

Return_type function_name(arg-type-1,arg-type-2,……..arg-type-n);

Example:

int my_square(int);

double amount(int,float,int);

void useless_msg(char[],int);

20 visit us: http://sites.google.com/site/kumarajay7th/

Function definition • An actual function is a snippet code that gets

executed.

• First line of function definition (known as function header) should be identical to function prototype with no semicolon.

• Example: int my_square(int x)

{

long int my_sq;

my_sq=x*x;

return my_sq;

}

21

Snippet code

visit us: http://sites.google.com/site/kumarajay7th/

Actual and Formal Parameter #include<stdio.h> int compute_sum(int,int); void main() { int sum,n1=10,n2=30; sum=compute_sum(n1,n2); printf(“total =%d”,sum); getch(); } int compute_sum(int x, int y) { return (x+y); }

22

Actual Arguments (or Actual Parameter)

Formal Parameter

Variable used in Calling function

Variable used in Called function

visit us: http://sites.google.com/site/kumarajay7th/

Actual & Formal Parameter example

#include<stdio.h> void plz_do_it(int); void main( ) { int a = 30 ; plz_do_it ( a ) ; printf ( "\n%d", a ) ; } void plz_do_it ( int b ) { b = 60 ; printf ( "\n%d", b ) ; }

23

Output: 60 30

#include<stdio.h> square (float); void main() { int a; printf(“\n enter a number”); scanf(“%f”,&a); printf(“%f”,square(a)); } square(float x) { return (x*x); }

Output Enter a number: 2 4.00000 Enter a number: 2.5 6.000000

Output Enter a number: 2 4.00000 Enter a number: 2.5 6.000000

wrong

visit us: http://sites.google.com/site/kumarajay7th/

24

Actual & Formal Parameter example #include<stdio.h> void plz_do_it(int); void main( ) { int a = 30 ; plz_do_it ( a ) ; printf ( "\n%d", a ) ; } void plz_do_it ( int b ) { b = 60 ; printf ( "\n%d", b ) ; }

24

Output: 60 30

#include<stdio.h> float square (float); void main() { int a; printf(“\n enter a number”); scanf(“%f”,&a); printf(“%f”,square(a)); } float square(float x) { return (x*x); }

Output Enter a number: 2 4.00000 Enter a number: 2.5 6.000000

Output Enter a number: 2 4.00000 Enter a number: 2.5 6.250000 Enter a number:1.5 2.250000

wrong

correct

visit us: http://sites.google.com/site/kumarajay7th/

Scope Rules

• The scope of a variable is in the program or function in which it is declared.

• A global variable is visible to all contained functions including the function in which the variable is declared.

• An entity* declared in the scope of another entity is always a different entity even if their names are identical.

entity*= variable, function, parameter

25 visit us: http://sites.google.com/site/kumarajay7th/

Scope Rule (contd…) 1. The scope of a variable is in the program or

function in which it is declared.

26

#include<stdio.h> void add(int,int); void mul(int,int); void main() { int a=20,b=10; add(a,b); mul(a,b); }

void add(int x1,int x2) { printf(“\n sum=%d”,x1+x2); }

void mul(int y1,int y2) { printf(“\n multiplication=%d”,y1*y2); }

Scope of variable a,b is within the main() only. Scope of variable x1,x2 is within the add() only. Scope of variable y1,y2 is within the mul() only.

visit us:http://sites.google.com/site/kumarajay7th/

Scope Rule (contd…)

2. A global variable is visible to all contained functions

including the function in which the variable is declared.

27

#include<stdio.h> int add_me(); int n1,n2; void main() { int my_sum; my_sum=add_me(); printf(“\n sum=%d”,my_sum); } /* end of main*/ int add_me(){ int result; Result=n1+n2; return result; }

Global variable

Local Variable A variable declared inside of a function. They are unknown to other function. i.e. scope is only within the function in which They are declared. Variable are Not accessed outside of function.

A variable declared outside of a function. They are known or accessed by any function comprising the program.

visit us: http://sites.google.com/site/kumarajay7th/

Scope Rules (contd…)

• An entity* declared in the scope of another entity is always a different entity even if their names are identical.

entity*= variable, function, parameter

28

Example; ??????

visit us: http://sites.google.com/site/kumarajay7th/

29

Parameter passing method

Pass by Value

Or Call by value

Pass by Reference

Or Call by Reference

Parameter passing method on the basis of argument (or parameter)

When the values of arguments are passed From the calling function to the called function, The values are copied into called function. If any changes made to the value in calling function, There is no change in the original values within the calling function.

Actual values are not passed, instead their addresses are passed. There is no copying of values since their memory locations are referenced. If any changes is made to value in called function, The original value gets changed within the calling function.

visit us :http://sites.google.com/site/kumarajay7th/

Call by values

30

//swaping the value by callByValue #include<stdio.h> void call_by_value(int,int); void main( ) { int a = 10, b = 20 ; call_by_value ( a, b ) ; printf ( "\na = %d \t b = %d", a, b ) ; } void call_by_value ( int x, int y ) { int t ; t = x ; x = y ; y = t ; printf ( "\nx = %d \t y = %d", x, y ) ; }

//no change in calling function #include<stdio.h> void no_change_value(int); void main( ) { int a = 30 ; no_change_value ( a ) ; printf ( "\na=%d", a ) ; } void no_change_value ( int b ) { b = 60 ; printf ( "\nb= %d", b ) ; }

Output: B=60 A=30

Output: x = 20 y = 10 a = 10 b = 20

visit us: http://sites.google.com/site/kumarajay7th/

Pointer (know it before using call by reference)

Let us take an example, int i=3;

This declaration tells the C compiler to:

(a) Reserve space in memory to hold the integer value.

(b) Associate the name i with this memory location.

(c) Store the value 3 at this location.

31

i

65524

Location name

Value at location

Location number

Memory map For i’s location

visit us: http://sites.google.com/site/kumarajay7th/

Pointer (contd…)

32

i

65524

Location name

Value at location

Location number

Memory map For i’s location

void main( ) { int i = 3 ; printf ( "\nAddress of i = %u", &i ) ; printf ( "\nValue of i = %d", i ) ; }

output: Address of i = 65524 Value of i = 3

%u=unsigned integer

First time used & in printf() indicating address of variable visit us: http://sites.google.com/site/kumarajay7th/

Pointer (contd…) &(address operator) and *(indirection operator)

33

main( ) { int i = 3 ; printf ( "\nAddress of i = %u", &i ) ; printf ( "\nValue of i = %d", i ) ; printf ( "\nValue of i = %d", *( &i ) ) ; } output: Address of i = 65524 Value of i = 3 Value of i = 3

main( ) { int i = 3 ; printf ( "\nAddress of i = %u", &i ) ; printf ( "\nValue of i = %d", i ) ; } output: Address of i = 65524 Value of i = 3

* is known as ‘indirection operator’ or

‘value at address’ visit us: http://sites.google.com/site/kumarajay7th/

Pointer (contd…)

34

main( ) { int i = 3 ; int *j ; j = &i ; printf ( "\nAddress of i = %u", &i ) ; printf ( "\nAddress of i = %u", j ) ; printf ( "\nAddress of j = %u", &j ) ; printf ( "\nValue of j = %u", j ) ; printf ( "\nValue of i = %d", i ) ; printf ( "\nValue of i = %d", *( &i ) ) ; printf ( "\nValue of i = %d", *j ) ; }

Output: Address of i = 65524 Address of i = 65524 Address of j = 65522 Value of j = 65524 Value of i = 3 Value of i = 3 Value of i = 3

Pointer variable (‘j’ in this case) contains address of other

variable (‘i’ in this case)

65524 3

i

65524

j

65522

visit us: http://sites.google.com/site/kumarajay7th/

Call by reference

35

//swapping the value by reference #include<stdio.h> void call_by_reference(int*, int*); void main( ) { int a = 10, b = 20 ; printf(“\n before swapping\n”); printf(“\n a=%d \t b=%d”,a,b); call_by_reference( &a, &b ) ; printf(“\n after swapping\n”); printf ( "\na = %d b = %d", a, b ) ; }

Output: before swapping a=10 b=20 after swapping a=20 b=10

void call_by_reference( int *x, int *y )

{ int t ; t = *x ; *x = *y ; *y = t ; }

visit us: http://sites.google.com/site/kumarajay7th/

Call by value vs call by reference

36

Call by value Call by reference

It consumes more memory space because formal parameter also occupies memory space.

It consumes less memory space because irrespective of data type of the actual arguments, each pointer occupies only 4 bytes

It takes more time to execute because the values are copied.

It takes less time because no values are copied.

visit us: http://sites.google.com/site/kumarajay7th/

Exercise

• Write a C program using function to find the numbers between 1 to 1000 which follows the property that 12 possesses. i.e.

(a) The number is 12

(b) Take it reverse (i.e.21) and square it (i.e. 441)

(c) Now take the square of 12 (i.e. 144)

(d) Compare the result of step (b) & step (c)

(e) If they are reverse of each other then print 12.

visit us: http://sites.google.com/site/kumarajay7th/ 37

Recursion(A recursive function)

• A function is called ‘recursive’ if a statement within the body of a function calls the same function.

• Sometimes called ‘circular definition’, recursion is thus the process of defining something in terms of itself.

• A situation in which a function calls itself either directly or indirectly.

38 visit us:http://sites.google.com/site/kumarajay7th/

Recursion (contd…)

visit us: http://sites.google.com/site/kumarajay7th/ 39

e.g. Recursion can be used to calculate factorial of a number. X!= x* (x-1)* (x-2)*(x-3)*…*2*1 However x! may be calculated as X!=x*(x-1)! And then (x-1)!= (x-1)*(x-2)! And then (x-2)!=(x-2)*(x-3)! ------------------------ ---------------------- And so on……

e.g. find the factorial of 4 4!=4*3*2*1 Or 4!=4*3!

Recursion example Q. find the factorial of a number using recursion

main( )

{

int a, fact ;

printf ( "\nEnter any number " ) ;

scanf ( "%d", &a ) ;

fact = rec ( a ) ;

printf ( "Factorial value = %d", fact ) ;

}

visit us: http://sites.google.com/site/kumarajay7th/ 40

rec ( int x ) { int f ; if ( x == 1 ) return ( 1 ) ; else return (x * rec ( x - 1 )) ; }

Recursion concept understanding

visit us: http://sites.google.com/site/kumarajay7th/ 41

return ( x * rec ( x - 1 )) ;

Important line

rec ( 5 ) returns ( 5 times rec ( 4 ), which returns ( 4 times rec ( 3 ), which returns ( 3 times rec ( 2 ), which returns ( 2 times rec ( 1 ), which returns ( 1 ) ) ) ) )

Recursion flow example

42 visit us: http://sites.google.com/site/kumarajay7th/

Starts here

Assignment on recursion

1. Find the factorial of a given number using recursion.

2. Generate fibonacci series upto nth terms using recursion

3. Define power function using recursion

4. Find the greatest common divisor (GCD) of 2 no.

5. Conversion from decimal to binary

visit us: http://sites.google.com/site/kumarajay7th/ 43

Special assignment on function

• Go through Let-Us-C of chapter function

• Try to generate your own function, say myf()

• Save a defined function myf() with new .cpp file name , say myf.cpp

• Save a new header file with declaring myf() prototype, say myf.h

• Add this header file myf.h to TurboC library

• Include this header file in your new file and execute the statement, #include ”myf.h”

1. do_it(). 2.print_me(). 3.add_me() 4.print_table()

visit us: http://sites.google.com/site/kumarajay7th/ 44

Data Storage in C

visit us: http://sites.google.com/site/kumarajay7th/ 45

1.Variable’s value stores at two location: • Memory and • CPU Register

2.Variable’s storage class tells us: Where the value would be stored. Default initial value Scope of a variable Life of a variable

visit us: http://sites.google.com/site/kumarajay7th/ 46

Data storage

Automatic

Register Static External

Type of Storage Class

Automatic Storage Class (keyword:auto)

• Storage- Memory

• Default Initial Value- garbage value

• Scope- local to the block in which variable is defined

• Life- within the block

visit us: http://sites.google.com/site/kumarajay7th/ 47

void main( ) { auto int i, j ; printf ( "\n%d %d", i, j ) ; } Output: 1211 221

Garbage value

void main( ) { auto int i = 1 ; { { { printf ( "\n%d ", i ) ; } printf ( "%d ", i ) ; } printf ( "%d", i ) ; } }

Output: 1 1 1

Automatic Storage class example

visit us: http://sites.google.com/site/kumarajay7th/ 48

void main( ) { auto int i = 1 ; { auto int i = 2 ; { auto int i = 3 ; printf ( "\n%d ", i ) ; } printf ( “\n%d ", i ) ; } printf ( “\n%d", i ) ; }

Output: 3 2 1

Register storage class

• Storage - CPU registers.

• Default initial value - Garbage value.

• Scope - Local to the block in which the variable is defined.

• Life - remains within the block in which the variable is defined.

visit us: http://sites.google.com/site/kumarajay7th/ 49

void main( ) { register int i ; for ( i = 1 ; i <= 10 ; i++ ) printf ( "\n%d", i ) ; }

Register variable is used to use the

variable frequently.

Static Storage class • Storage − Memory.

• Default initial value − Zero.

• Scope − Local to the block in which the variable is defined.

• Life − Value of the variable persists between different function calls.

visit us:http://sites.google.com/site/kumarajay7th/ 50

void main( ) { increment( ) ; increment( ) ; increment( ) ; }

increment( ) { static int i = 1 ; printf ( "%d\n", i ) ; i = i + 1 ; }

Output: 1 2 3

auto int i=1; Output: 1 1 1

External Storage Class (keyword:extern)

• Storage − Memory. • Default initial value − Zero. • Scope − Global. • Life − As long as the program’s execution doesn’t come to an end.

visit us: http://sites.google.com/site/kumarajay7th/ 51

int i ; main( ) { printf ( "\ni = %d", i ) ; increment( ) ; increment( ) ; decrement( ) ; decrement( ) ; }

increment() { i = i + 1 ; printf ( "\non incrementing i = %d", i ) ; }

decrement( ) { i = i - 1 ; printf ( "\non decrementing i = %d", i ) ; }

Output: i = 0 on incrementing i = 1 on incrementing i = 2 on decrementing i = 1 on decrementing i = 0

Extern Storage Class Example

int x = 21 ;

void main( )

{

extern int y ;

printf ( "\n%d %d", x, y ) ;

}

int y = 31 ;

visit us:http://sites.google.com/site/kumarajay7th/ 52

Declaring a variable

Defining a variable

global

global

Requires no space

space gets reserved

Extern storage class example (contd…)

visit us: http://sites.google.com/site/kumarajay7th/ 53

int x = 10 ; main( ) { int x = 20 ; printf ( "\n%d", x ) ; display( ) ; } display( ) { printf ( "\n%d", x ) ; }

Global x

Local x Confused ?

Output: 20 10

Preference is given to local variable

Excercise

• From Let-Us-C

visit us:http://sites.google.com/site/kumarajay7th/ 54