Transcript

Functions in CA brief study

Functions

• Function is a self-contained block or a sub-program of one or more statements that performs a special task when called.

Example of functions

• Hotel management

– Front Office

– Reservation

– Housekeeping

– Telephone

Hotel management

Hotel

Customer()

{

House_keeping(); //Function call

}

House_keeping() //Function definition

{

Cleans rooms;

}

Hotel

Customer() //calling function

{

House_keeping(); //Function call

}

House_keeping() //called function

{

Cleans rooms;

}

Add two numbersmain()

{

int a,b;

int c;

printf(“Enter the value of a”);

scanf(“%d”,&a);

printf(“Enter the value of b”);

scanf(“%d”,&b);

c=a+b;

printf(“Answer is:%d”,c);

}

Add two numbers using functionsmain()

{ add(x,y)

int a,b; {

int c; z=x+y;

printf(“Enter the value of a”); printf(“%d”,z);

scanf(“%d”,&a); }

printf(“Enter the value of b”);

scanf(“%d”,&b);

add(a,b);

}

Arguments/Parameters

• Arguments are used mostly in functions.

• it can be any input parameter which a function can use to do it's work.

• Example: sin(x) sin is a function

x is it's argument.

Arguments/Parameters

• Actual arguments:

• Arguments of calling function

• Formal arguments:

• Arguments of called function

Add two numbers using functionsmain() formal arguments

{ add(x,y)

int a,b; {

int c; z=x+y;

printf(“Enter the value of a”); printf(“%d”,z);

scanf(“%d”,&a); }

printf(“Enter the value of b”);

scanf(“%d”,&b);

add(a,b); //function call

} actual arguments

Argument/Parameter list

a=2

b=4

add(a,b);

add(x,y)

x=2

y=4

return statement

• function uses return statement to return the value to the called function.

• Exit from the called function.

return(expression);

Hotel

Customer() //calling function

{

House_keeping(); //Function call

}

House_keeping() //called function

{

Cleans rooms;

return 0;

}

Hotel

Customer() //calling function

{

Front_office(Money); //Function call

}

Front_office(Money) //called function

{

return receipt;

}

Types of functions

1. No arguments and no return type

2. No arguments and return type

3. With arguments and no return type

4. With arguments and return type

Passing arguments

• The arguments passed to function can be of two types.

1. Values passed – Call by value

2. Address passed – Call by reference

Call by value• main()

{ int x=50, y=70; add(x,y); }

add(int x1,int y1) { int z1; z1=x1+y1; printf(“%d”,z1); }

Call by reference• main()

{ int x=50, y=70; add(&x,&y); }

add(int *x1,int *y1) { int z1; z1=x1+y1; printf(“%d”,z1); }

Call by reference

• Address is passed using symbol ‘&’

value is accessed using symbol ‘*’

x=50 &x=2000 *x=50

y=70 &y=2008 *y=70

Thank you