Chap 9(functions)
-
Upload
bangabandhu-sheikh-mujibur-rahman-science-and-technology-university -
Category
Education
-
view
20 -
download
1
Transcript of Chap 9(functions)
User-defined FunctionsTopics Function and it’s advantages Form of C Function Calling function
Function and it’s advantages Function: A set of statement(s) to solve
certain kind of problem is called function. Each function has it’s own name. Ex: printf(), scanf(), sqrt() etc.
Advantages of Function in C:1. The length of source program can be reduced.2. It is easy to locate and isolate a faulty function.3. A function may be used by many other function.
Classification of Function Functions can be classified into two
categories.
1. Built in function: The function which is build in the C is called built in function. Ex: printf(), scanf(), getch().
2. User defined function: The functions which are designed by programmer called user defined function.
Form of C Function The form of function:
return_type function_name(argument list)
{
local variable declarations;
statement(s);
return(expression);
} Here argument list contains valid variable names
separated by commas. Return_type is the type of the data returned from function.
Continue… Example of function:
int add(int a, int b)
{
int sum;
sum= a+b;
return(sum);
}
Calling of Function We can call C function by mentioning the
name with appropriate argument. Example of calling:
main()
{
int x=10, y=20,z;
z = add(x,y);
printf(“Summation = %d”,z);
}
Call by Value In this case of function calling, the value of actual
parameter is passed to the formal parameter. Here constant value or variable can be used as actual parameter. If we change the value of formal parameter then there is no effect in actual parameter.
void change(int x){ x = x + 10;}main(){ int k = 10; change(k); printf(“%d”,k);}
Call by Reference Here the address of actual parameter is passed to the
formal parameter. We cannot use address directly. If we change the value of formal parameter then the value of actual parameter also changed.
Void change(int *x){ *x = *x+10;} main(){ int k=10;
change(&k); printf(“%d”,k);}
Nesting of C Function C permits nesting of functions freely. Function1 can call function2,
function2 can call function3,……….and so on. main()
{ int a,b,c; function1();}function1(){
……. function2();}function2(){………}
Recursion When a function calls itself is called
recursion. Simple example- main()
{ printf(“This is Recursion”); main();} When executed, the output like
This is RecursionThis is RecursionThis is
Continue.. A recursive function for factorial:
int factorial(int n)
{
if(n==0)
return(1);
else
return(n*factorial(n-1));
}
Function with Array Like the values of simple variables, it is also
possible to pass the values of an array to a function.
main() { static int value[ ]={10,45,25,40}; printf(“Largest value: %d”,maximum(value,4));}int maximum(int x[ ], int n){ int i, max=0; for(i=0;i<n;i++) if(max<x[i])
max=x[i]; return(max);}