Presentation is loading. Please wait.

Presentation is loading. Please wait.

FUNCTIONS. C function can be classified into two categories, namely, library functions and user – defined functions. main is an example of user – defined.

Similar presentations


Presentation on theme: "FUNCTIONS. C function can be classified into two categories, namely, library functions and user – defined functions. main is an example of user – defined."— Presentation transcript:

1 FUNCTIONS

2 C function can be classified into two categories, namely, library functions and user – defined functions. main is an example of user – defined functions. printf and scanf belong to the category of library functions. We have also used other library functions such as sqrt, cos, strcat, etc. The main distinction between these two categories is that library functions are not required to be written by us whereas a user – defined function has to be developed by the user at the time of writing a program. Introduction

3 Function COND… FUNCTION DECLARATION FUNCTION DEFINITION FUNCTION CALL

4 Function #include int mod(int, int); /* Function Prototype */ void main() { printf("The mod is: %d ", mod(4,5));/* Function calling */ } int mod(int x, int y) /* Function Definition */ { return x % y; }

5 FUNCTION DEFINITION SYNTAX A function definition, also known as function implementation shall include the following elements. 1. Function Name 2. Function Type 3. List of Parameters 4. Local variable declarations 5. Function Statements 6. A Return statement All the six elements are grouped into two parts, namely, 1. Function header (First three Elements) 2. Function Body (Second three Elements) function_type function_name(parameter_list) { local variable declaration; executable statement_1; executable statement_2; --------------------------------- return statement; } Example: float mul ( float x, float y) { float result; result = x * y; return (result); }

6 FUNCTION PROTYPING OR FUNCTION DECLARATION A function prototype is a very important feature of modern C programming It must be added to a C program just before the main function, if we call that function before defining it It tells the compiler what type of value the function returns, numbers and types of parameters, and order in which these parameters are expected. There is no need for a prototype if the function is called after its definition

7 FUNCTION DECLARATION SYNTAX Like variables, all functions in a C program must be declared, before they are invoked, A function declaration (also known as function prototype) consists of four parts. 1. Function type (return type) 2. Function name 3. Parameter list 4. Terminating semicolon The general format is Function_type function_name(parameter_list); Example: float mul (float x, float y);

8 Function Definition A simple format of a C function definition is as follows: return-value-type function- name(parameters) { Declarations; Statements; Return (expression); } Function Prototype

9 WORKING PRINCIPLES

10 Formal and Actual Parameters In C, there are two types of parameters Formal parameters appear in the prototype and definition, and are representative of the data types the function expects to receive Actual parameters appear only in a function call and are the actual data passed

11 Example #include void MyFun( int ); Formal Parameter int main( void ) { int x=3; printf( “x has a value of %d”, x); MyFun( x );Actual Parameter printf( “x has a value of %d”, x); return 0;Parameter Passing } void MyFun( int x ) Formal Parameter { printf( “x has a value of %d”, x); x = 77; printf( “x has a value of %d”, x); }

12 CATEGORIES OF FUNCTIONS Category 1 : Functions with no arguments and no return values. Category 2 : Functions with arguments and no return values. Category 3 : Functions with arguments and one return value. Category 4 : Functions with no arguments but return a value. Category 5 : Functions with default arguments.

13 Function with No return type and No arguments Void func1(); void main() { ……. func1(); ……. } void func1() { ……. }

14 #include void add(); void main() { add(); } void add() { int a,b,c; printf(“enter any two numbers”) scanf(“%d%d”,&a,&b); c= a+b; printf(“the addition of %d and %d is %d”,a,b,c); }

15 Function with No return type and with arguments void func1(int,int); void main() { ……. func1(x,y); ……. } void func1 (int a,int b) { ……. }

16 #include void add(int,int); void main() { int x,y,c; printf(“enter any two numbers”) scanf(“%d%d”,&x,&y); add(x,y); } void add(int a,int b) { int c; c= a+b; printf(“the addition of %d and %d is %d”,a,b,c); }

17 Function with return type and with arguments int func1(int,int); void main() { ……. a=func1(x,y); ……. } int func1(int a,int b) { ……. }

18 #include int add(int,int); Void main() { int x,y,c; printf(“enter any two numbers”) scanf(“%d%d”,&x,&y); c = add(x,y); printf(“The Result = %d ”,c); } int add(int a,int b) { int c; c= a+b; return (c); }

19 Function with return type and No arguments int func1(); void main() { ……. a=func1(); ……. } int func1() { ……. }

20 #include int add(); Void main() { int c; c = add(); printf(“The Result = %d ”,c); } int add() { int a,b,c; printf(“enter any two numbers”) scanf(“%d%d”,&a,&b); c= a+b; return (c); }

21 Function without a prototype #include int sum(int x, int y) { return x+y; } void main() { printf("The sum is: %d ", sum(4,5)); }

22 Storage class Every variable or constant possesses a data type In addition to the data type, a variable possesses an attribute called storage class. where v1,v2 are the variables data_type is the valid data type in c language storage_class gives information regarding lifetime and scope. Storage_class data_type v1,v2,v3,………………..vn.

23 Storage class cont’ Lifetime Lifetime or Longetivity of a variable refers to the duration for which the variable retains a given value during the execution of a program. Scope It is the portion of the program in which the variable may be visible or available.It can classified into two types Type 1: Local variable (or) private variable (or) internal variable. Type 2: Global variable (or) public variable (or) external variable.

24 Types Sl.NoTypes of Storage ClassReserved words 1Automaticauto 2Registerregister 3Staticstatic 4Externalextern

25 Automatic variables By default all variables are automatic storage class. Their memory space is automatically allocated as the variable is declared. These variables are given only temporary memory space and after the execution all the automatic variables will get disposed. It can not be accessed directly by other functions.

26 #include void fun(int); void main() { int i; a=10; fun(a); } void fun(int a) { prinf("%d",a); } #include void fun(); void main() { int i; a=10; fun(); } void fun() { prinf("%d",a); //error }

27 Sample Program #include Void main() { float f1 = 10.2; { float f1 = 40.00; { float f1 = 33.9; printf(“the value of f1 in block 3 is %f”,f1); } printf(“the value of f1 in block 2 is %f”,f1); } printf(“the value of f1 in block 1 is %f”,f1); }

28 External variables It refers to the location outside a block i.e., prior to the main() or beyond the closing braces ( } ) of the outermost block in a program. The value is available throughout the program because of its global scope. Whenever an external variable is modified in a block, the effect is propagated to all places where ever it is used.

29 #include int a; void fun(); void main() { int i; a=10; fun(); } void fun() { prinf("%d",a); }

30 Static Variables The variables are declared with static keyword. It can be internal static (or) external static based on the place of its declaration. Both are declared using the keyword static. The storage used by an static variable in a block is not lost after the completion of the execution. Even after the termination of the block, the value of the static variable is available. If the value is changed during the execution the recent value is retained. When the execution enters the next time the same block, the initialiser is neglected and the recently stored value is retained.

31 #include static int count; void main() { int i,x; printf("\ncount is %d",count); getch(); } #include static int count; void func(); void main() { int i,x; printf("\n%d",count); count++; func(); printf("\n%d",count); getch(); } void func() { printf("\n%d",count); }

32 Sample Program #include int fun(int); void main() { int i,x; for(i=1;i<=10;i++) { x = fun(i); printf(“The I value is %d”,x); } int fun(int a) { auto int sum = 100; sum = sum + a; return(sum); } #include int fun(int); void main() { int i,x; for(i=1;i<=10;i++) { x = fun(i); printf(“The I value is %d”,x); } int fun(int a) { static int sum = 100; sum = sum + a; return(sum); }

33 Output When sum is auto The I Value is:101 The I Value is:102 The I Value is:103 The I Value is:104 The I Value is:105 The I Value is:106 The I Value is:107 The I Value is:108 The I Value is:109 The I Value is:110 When sum is static The I Value is:101 The I Value is:103 The I Value is:106 The I Value is:110 The I Value is:115 The I Value is:121 The I Value is:128 The I Value is:136 The I Value is:145 The I Value is:155

34 Register Variables The variables are declared using register keyword. The scope and lifetime is same as that of automatic variables. For any given operation the data available in the memory should be transferred to the CPU registers. So if the data are stored in register itself then the time for data transfer from the memory to the register is saved. Only a few values can be placed at a time and hence it is advisable to use limited register variables. main() { register int i; for(i=0;i<10;i++) printf(“%d”,i); }

35 Parameter Passing Methods In C there are two ways of passing parameters to a function Call by Value Call by Reference

36 Call by value  Copy of data passed to function  Changes to copy do not change original  Prevent unwanted side effects This Method copies the value of actual parameters(calling program) into the formal parameters(called program) of the functions. Here the changes of the formal parameters cannot affect the actual parameters. Because only the copy of actual arguments were passed. A function can return only one value per call.

37 Example #include int cube (int) void main() { int n=5; printf(“Cube of %d is %d”,n,cube(n)); } int cube (int x); { x=x*x*x; return x; } O/p: Cube of 5 is 125

38 Call by reference  Function can directly access data  Changes affect original It is another way of passing parameter to the functions here the address of arguments are copied into the parameters inside the functions. The address is used to access the actual arguments used in the call. By using this we can make a function to return more the one value(indirectly).

39 Example #include void interchange (int *a, int *b) void main() { int i=5,j=10; printf(“Before : I and J value is %d and %d”,I,j); interchange(&i,&j); printf(“After : I and J value is %d and %d”,I,j); } void interchange (int *a, int *b) { int t; t=*a *a=*b *b=t } O/p: Before : I and J value is 5 and 10 After : I and J value is 10 and 5

40 Call by value Vs Call by reference Call by value  Copy of data passed to function  Changes to copy do not change original  Prevent unwanted side effects Call by reference  Function can directly access data  Changes affect original

41 #include void swap(int, int); void main() { int num1, num2; num1 = 10; num2 = 20; swap ( num1, num2 ); printf("%d %d\n", num1, num2); } void swap(int val1, int val2) { int temp; temp = val1; val1 = val2; val1 = temp; }

42 Swap two integers using call by value(cont.) In the above example, we passed parameters by value, a copy is made of the variable and thus any change made to the parameters val1 and val2 will not be passed back to the main function The main function will not know anything about the swapping of val1 and val2 Therefore, the output of the above program will be ….? Normally if we wished to pass back a value we would use return or we would pass the parameters by reference

43 Nested Functions In C, it provides a facility to write one function with in another function. This is called nesting of functions Main() { --------- func1(); --------- } func1() { --------- func2(); --------- } func2() { --------- }

44 Recursion

45 Recursion is a process of calling the same function itself again and again until same condition is satisfied. This is used for repetitive computation in which each action is satisfied in terms of a previous result A function can call itself –Directly –Indirectly Function1() { ----- Function1(); ----- }

46 Recursion vs. Iteration Repetition –Iteration: explicit loop –Recursion: repeated function calls Termination –Iteration: loop condition fails –Recursion: base case recognized Both can have infinite loops Balance between performance (iteration) and good software engineering (recursion)

47 Sl.No.IterationRecursion 1. Iteration explicitly user a repetition structure. Recursion achieves repetition throught repeated function calls. 2. Iteration terminates when the loop continuation condition fails. Recursion terminates when a base case is reached. 3. Iteration keeps modifying the counter until the loop continuation condition fails. Recursion keeps producing simple versions of the original problem until the base case is reached. 4. An infinite loop occurs when the loop step continuation test never becomes false. An infinite loop occurs if the recursion doses not reduce the problem each time in a manner that converges the base case. 5. Iteration normally occurs within a loop so extra memory assignment is omitted. Recursion causes another copy of the function & hence a considerable memory space is occupied. 6. It reduces the processor operating time. It increases the processor operating time. Difference Between Iteration and Recursion

48 Example: fibonacci.c function Fibonacci ( n ) { if ( n is less than or equal to 1 ) then return n else return Fibonacci ( n - 2 ) + Fibonacci ( n - 1 ) } /* Compute the n-th Fibonacci number, when=0,1,2,... */ long fib ( int n ) { if ( n <= 1 ) return n ; else return fib( n - 2 ) + fib( n - 1 ); }

49 int main(void) { int number; printf("Enter number: "); scanf("%d", &number); printf("Fibonacci(%d) = %ld\n", number, fib(number)); return 0; } Example: fibonacci.c Sample main() for testing the fib() function:

50 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

51 Scope: Local Variables Formal parameters: only accessible whilst a function is executing Variables declared in a function body: only accessible whilst the function is executing In fact, this is true of every block in a program

52 C Standard Library Every implementation of C comes with a standard library of predefined functions. Note that, in programming, a library is a collection of functions. The functions that are common to all versions of C are known as the C Standard Library.

53 C Standard Library Function Examples Function Name Math Name ValueExample abs(x) absolute value |x||x| abs(-1) returns1 sqrt(x) square rootx 0.5 sqrt(2.0) returns1.414 … exp(x) exponentialexex exp(1.0) returns2.718 … log(x) natural logarithm ln x log(2.718…) returns1.0 sin(x) sinesin x sin(3.14…) returns0.0 cos(x) cosinecos x cos(3.14…) returns tan(x) tangenttan x tan(3.14…) returns0.0 ceil(x) ceiling ┌ x ┐ ceil(2.5) returns3.0 floor(x) floor └ x ┘└ x ┘ floor(2.5) returns2.0


Download ppt "FUNCTIONS. C function can be classified into two categories, namely, library functions and user – defined functions. main is an example of user – defined."

Similar presentations


Ads by Google