Wednesday, 8 January 2014

C Programming Language Tutorial XI – Function (User Defined Function)

Function(User Define Function)
Definition
Function is a sub program or sub routine which is always calls in main program to perform particular operation.
Function is a set of instructions to perform well define specific task.
Advantages
§ Avoid repetition of code.
By using function we crate section of code to calculate result, later in same program, the same calculations has to be done by using different set of values then we use function instead of writing same instructions all over again. Thus it avoids repetition of code.
§ Main program is reduce
Definition of function is always outside the main program & with program we only give call to function therefore main program is reduce.
§ Memory management
Whenever we call function, then during function execution memory allocate & after execution memory block is release therefore program written under function allocate less memory as compare to normal program. By using function we can be save a lot of memory.
§ Modular approach
By using function a large program has to be split into smaller segment known as modules. So that program structure is more simplified and easy to understand.
Function Rules
Ø  A pair of parenthesis must follow the function name.
Ø  The values pass to function known as arguments or parameters.
Ø  The arguments pass to function separated by comma.
Ø  Arguments appearing in the parenthesis at function definition part known as formal arguments
Ø  Arguments appearing in the parenthesis at function call known as actual arguments.
Ø  A set of parenthesis is compulsory either function having arguments or without any argument.
Ø  Semicolon is used at the end of function when function is call but it is not allowed at function definition.
Ø  At a time only one value can be return by function.
Types of Variables
In case of function two types of variable useful namely local and global variables.
Local Variables
Local variables created upon entry into its block and destroy upon exit from block. Their contents are lost once block is over. Their values are local to that function only in which these variables are declared.
For example:
void getdata()
{
  int x;  //local variable
   -------;
}
Global Variables
Global variables declared outside the all functions and at the top of the program i.e. above main(). They are hold contents throughout the execution of program. This variables are useful when many functions in a program can share same data.
For example:
int x;  //global variable
void main()
{
-------;
}
If you watch inbuilt functions carefully then you can find that when we called functions in program then these functions have different syntax. Functions accept either single, multiple or do not accept any argument. Whether the functions have argument or do not have argument is depends upon definition of function. While defining function you have to decide function has how many arguments as per requirement of given logic.
Let us simplify this concept by following programs. These programs are introduction of function.
//function without any argument
#include<stdio.h>
#include<conio.h>
void main()
{
 clrscr();
 myline();                    //calling myline() function that is defined by user
 printf("\nWelcome\n");
 myline();
 printf("\nHello\n");
 myline();
 getch();
}
myline()                     //definition of function
{
 int i;
 for(i=1;i<=50;i++)
 {
  printf("-");
 }
}
o/p:
--------------------------------------------------
Welcome
--------------------------------------------------
Hello
--------------------------------------------------
//function with single argument
#include<stdio.h>
#include<conio.h>
void main()
{
  clrscr();
  myline('#');         //single character passed as an argument
  printf("\nHello\n");
  myline('$');
  printf("\nWelcome\n");
  myline('&');
  getch();
}
myline(char ch)    //whenever function is called then each time current character stored in ch
{
  int i;
  for(i=1;i<=50;i++)
  {
    printf("%c",ch);
  }
}
o/p:
##################################################
Hello
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
Welcome
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
//function with multiple arguments
#include<stdio.h>
#include<conio.h>
void main()
{
  clrscr();
  myline('#',10);      //single character and integer value passed as an argument
  printf("\nHello\n");
  myline('%',20);
  printf("\nWelcome\n");
  myline('&',30);
  getch();
}
myline(char ch, int n)
{
  int i;
  for(i=1;i<=n;i++)
  {
    printf("%c",ch);
  }
}
o/p:
##########
Hello
%%%%%%%%%%%%%%%%%%%%
Welcome
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
Now let us begin with logical and technical view of function.
Anatomy of Function
§ Function header.
§ Defines function name, return type, the number of types of parameters.
§ Information flow to a function.
§ Local variables.
§ Function body.
§ Return statement.
Prototype Function
Declaration of function which is defines name, return type and the number of types of arguments.
return type function_name(data type of arguments);
It is either declare above main or inside main method.
Return Statement
Once called function finished execution then return statement returns a value to the calling function. When the return statement is encountered the execution of called function gets terminated and program control immediately passed to the calling function.
return;
It does not return any value
return(expression);
It returns value to the calling function.
A function does not return any value then return type is void.
In above program you have used only function definition and calling of function part. Now look at following program where function declaration is included.
#include<stdio.h>
#include<conio.h>
void myline(char,int);  //declaration part
void main()
{
 ---------
 ---------
 myline(‘#’,10);              //calling part
 ----------
 ----------
}
void myline(char ch,int n)    //definition part
{
  ---------
  ---------
}
Executing Functions 
Function can be execute by using two ways
1. Function call by value
2. Function call by reference
Function call by value
Changes made in function are directly not reflected into main() program. In this case, value of variables is passed as an argument from main() to function. Any changes made in formal argument in function part are directly not get reflected back into main() program.
  
Before starting study of these programs you have to read and study programs of C       Programming Language Tutorial VII, VIII, IX.
//By function program to print addition of two numbers
#include<stdio.h>
#include<conio.h>
int addno(int,int); //prototype function
void main()
{
 int no1,no2,s;
 clrscr();
 printf("\nEnter any two numbers: ");
 scanf("%d%d",&no1,&no2);
 s = addno(no1,no2); //actual argument
 printf("\nAddition = %d",s);
 getch();
}
 int addno(int a,int b) //formal argument
 {
  int t;
  t = a+b;
  return(t);
 }
o/p:
Enter any two numbers: 12 43
Addition = 57
You can write all the programms those are created in previous lesson by using function call by value.
Let us see some programms
//prog to calculate factorial of number by function
#include<stdio.h>
#include<conio.h>
long factno(int);     //it returns long int
void main()
{
 int no;
 long f;
 clrscr();
 printf("\nEnter any number: ");
 scanf("%d",&no);
 f = factno(no);  
 printf("\nFactorial of number = %ld",f);
 getch();
}
long factno(int n)
{
 long fact=1;
 while(n>0)
 {
   fact = fact * n;
   n--;
 }
 return(fact);
}
The series is 1+52+93+134+.............. till user defined range
Series(ser) starts from one, base number(bno) starts from one and power(p) starts from one. Series goes till user defined range. Series and power increment by one whereas base number increment by 4. Result is sum of series.
//prog to find answer of series
#include<stdio.h>
#include<conio.h>
int power(int,int);
void main()
{
 int bno,pow,ser,range;
 long int result=0;
 clrscr();
 printf("\nEnter range for series: ");
 scanf("%d",&range);
 for(ser=1,bno=1,pow=1;ser<=range;ser++,bno+=4,pow++)
 {
  result = result + power(bno,pow);
 }
 printf("\nResult of series = %ld",result);
 getch();
}
int power(int b,int p)  //power is calculate
{
 int ans=1;
 while(p>=1)
 {
  ans = ans * b;
  p--;
 }
 return(ans);
}
O/p:
Enter range for series: 3
Result of series = 755
Function call by reference

Changes made in function are directly reflected into main() program. In this case, instead of variables, it’s address is passed as an argument from main() to function. Any changes made in formal argument in function part are directly get reflected back into main() program. This type of function is used in case of array, structure and pointer

No comments:

Post a Comment