53
FUNCTIONS

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

Embed Size (px)

Citation preview

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

FUNCTIONS

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

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

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

Function COND…

• FUNCTION DECLARATION

• FUNCTION DEFINITION

• FUNCTION CALL

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

Function #include <stdio.h>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; }

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

FUNCTION DEFINITION SYNTAXA 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);}

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

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

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

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);

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

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

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

WORKING PRINCIPLES

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

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

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

Example #include <stdio.h>void MyFun( int ); Formal Parameterint 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);}

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

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.

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

Function with No return typeand No arguments

Void func1();

void main()

{

…….

…….

…….

func1();

…….

}

void func1()

{

…….

…….

…….

…….

}

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

#include<stdio.h>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);

}

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

Function with No return typeand with arguments

void func1(int,int);

void main()

{

…….

…….

…….

func1(x,y);

…….

}

void func1 (int a,int b)

{

…….

…….

…….

…….

}

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

#include<stdio.h>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); }

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

Function with return typeand with arguments

int func1(int,int);

void main()

{

…….

…….

…….

a=func1(x,y);

…….

}

int func1(int a,int b)

{

…….

…….

…….

…….

}

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

#include<stdio.h>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);

}

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

Function with return typeand No arguments

int func1();

void main()

{

…….

…….

…….

a=func1();

…….

}

int func1()

{

…….

…….

…….

…….

}

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

#include<stdio.h>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);

}

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

Function without a prototype

#include <stdio.h>int sum(int x, int y) { return x+y; }void main() { printf("The sum is: %d ", sum(4,5)); }

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

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.

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

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.

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

Types

Sl.No Types of Storage Class Reserved words

1 Automatic auto

2 Register register

3 Static static

4 External extern

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

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.

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

#include<stdio.h>#include<conio.h>void fun(int);void main(){

int i;a=10;fun(a);

}void fun(int a){

prinf("%d",a); }

#include<stdio.h>#include<conio.h>void fun();void main(){

int i;a=10;fun();

}void fun(){

prinf("%d",a); //error}

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

Sample Program#include<stdio.h>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);}

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

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.

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

#include<stdio.h>#include<conio.h>int a;void fun();void main(){

int i;a=10;fun();

}void fun(){

prinf("%d",a);}

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

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.

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

#include<stdio.h>#include<conio.h>static int count;void main(){

int i,x;printf("\ncount is %d",count);getch();

}

#include<stdio.h>

#include<conio.h>

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);

}

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

Sample Program

#include<stdio.h>#include<conio.h>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<stdio.h>#include<conio.h>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);

}

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

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

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

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);}

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

Parameter Passing Methods

• In C there are two ways of passing parameters to a function

Call by ValueCall by Reference

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

Call by value

Copy of data passed to functionChanges to copy do not change originalPrevent 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.

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

Example#include <stdio.h>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

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

Call by reference Function can directly access dataChanges 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).

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

Example#include <stdio.h>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

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

Call by valueVs

Call by reference • Call by value

Copy of data passed to functionChanges to copy do not change originalPrevent unwanted side effects

• Call by reference Function can directly access dataChanges affect original

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

#include <stdio.h>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;

}

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

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 aboutthe swapping of val1 and val2 Therefore, the output of the above program will be….?

• Normally if we wished to pass back a value wewould use return or we would pass the parametersby reference

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

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(){------------------------------------}

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

Recursion

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

Recursion

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();

-----}

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

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)

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

Sl.No. Iteration Recursion

1. Iteration explicitly user a repetitionstructure.

Recursion achieves repetition throughtrepeated function calls.

2. Iteration terminates when the loopcontinuation condition fails.

Recursion terminates when a base case is

reached.

3. Iteration keeps modifying the counteruntil 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 amanner that converges the base case.

5. Iteration normally occurs within a loop so

extra memory assignment is omitted.

Recursion causes another copy of thefunction & hence a considerable memoryspace is occupied.

6. It reduces the processor operating time.

It increases the processor operating time.

Difference Between Iteration and Recursion

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

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 );}

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

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:

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

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

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

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

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

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.

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

C Standard Library Function ExamplesFunctionName

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

sin(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