Wednesday, April 4, 2012

Functions

A function is used to perform a specific operation in your program.

The functions are your best and safest bet when moving on to large programs. You cannot just start your program and combine all your program's functionalities within the main function itself. Whenever you indulge in writing programs of large size, always try to use different functions for different operations your program does.

Dividing the program into functions has the following advantages :
  1. Get a better grasp of your program.
  2. You can reuse your function whenever necessary without writing it over and over again.
  3. Do not let your own program confuse you to the bitter end.
A sample program would help you better understand it. Suppose you want to find the factorial of 5 numbers, without using functions, you need to write the loops over and over for 5 times. But with function you dont have to do that. :
Factorial Program without using a seperate function : 
#include<stdio.h>
void main()
{
 int no[2]={4,5},factorial[2];
 int fact=1,i;
 for(i=1;i<=no[0];i++)
 {
  fact = fact*i;
 }
 factorial[0]=fact;
 printf("\n The factorial of %d is %d",no[0],factorial[0]);
 fact=1;
 for(i=1;i<=no[1];i++)
 {
  fact = fact*i;
 }
 factorial[1]=fact;
 printf("\n The factorial of %d is %d\n",no[1],factorial[1]);
} 
Factorial Program with a seperate function :
#include<stdio.h>
int factorial(int num) /* Function that returns integer data type */
{
 int factorial_result=1,i;
 for(i=1;i<=num;i++)
 {
  factorial_result = factorial_result*i;
 }
 return factorial_result; /* Return the factorial result to the calling function */
}
void main()
{
 int no[2]={4,5},fact[2],fact_sec_num;
 printf("\n The factorial of %d is %d ",no[0],factorial(no[0]));
 /* Call the function within printf statement */
 fact_sec_num = factorial(no[1]);
 /* Assign the value returned to fact_sec_num */
 printf("\n The factorial of %d is %d ",no[1],fact_sec_num);
}
When you look at the above example, the first one seems to be redundant and occupying more space which reduces the readability and understanding of the program.

But the second one is pretty much self-explanatory. Whenever you need to calculate the factorial for a number, just call the function instead of writing code for it again and again.

Function Declaration and Definition :
A function can be defined as follows :
return-type function-name(data-type argument-1,data-type argument-2,......)
{
     /* Function Statements - Your function body goes here */
}

No comments:

Post a Comment