functions

Functions

A function is complete program in itself, in the sense that its structure is similar to c main() function except that the name main() is replaced by the name of the function.

The general form of the function

Type name of function (arguments){
Body of function
}

demonstration

int sum(int a, int b){
int sum= a+b;
return (sum);
}

Types of functions

  • Library functions
  • User define functions

Library functions  These function are predefined in the compiler of a language and stored in a special library file. E.g#include<math.h> for mathematical function.

User define functions:  A function is a self contained block of statements that carries out some specific , well defined task specified by the user and is called as user defined function.

Demonstration of user defined function.

#include<stdio.h>
#include<conio.h>
void main(){
printf(“this is main function”);
fun1();
fun2();}
fun1(){
printf(“this is function 1 definition”);}
fun2(){
printf(“this is function 2 defination”);}
}
}
}

There is 3 steps to work with function

  1. Function prototype
  2. Function definition
  3. Function call

If we create a function named sum , the function of this function is to add the number of two variable . so we need to create a function  for the sum , and then when we need to use this created function in a program we can call this function.
Definition of Function to add to number

int sum (int x, int y)
{
int s;
s=x+y;
return (s);
}

Call to a function
In this part we call the function mean we will use the function defined for particular task in a program

#include<stdio.h>
#include<conio.h>
void main(){
int funsum(int, int);
/*this is function prototype*/
int n1, n2, sum;
/*n1, n2 and sum are variables having integer data type*/
clrscr();
printf(“enter two numbers”);
scanf(“%d%d”,&n1,&n2);
sum=funsum(n1,n2);
/*funsum with arguments n1 and n2 are the function call*/
printf(“sum of %d  and %d is =%d”, n1,n2,sum);
getch();
}
/*function definition*/
int calsum(int a, int b){
int s;
s=a+b;
return(s);
}

Output : enter three numbers 10 30
Sum of 10 and 30 is = 40

Variations in functions

1. Function with no arguments and no return value.
2. Function with argument but no return value.
3. Function with no arguments but return a value.
4. Function with arguments and return value.

Passing argument to a function:

  1. Call by value
  2. Call by reference

Call by value  In this type of parameter passing , only the values are passed from the calling function to the called function.
Call by reference This is technique passes the addresses or references of the actual parameters to the called function.

Requirement address of operator & to the actual parameters in the function call and the value at address operator * to the formal parameters.