Function
Functions are frequently used in C
to minimize a series of instructions that are to be executed more than once. A
loop can repeat a series of instructions only if each iteration immediately
follows the previous one. Calling of function can cause a series of
instructions to be repeated at any point within the program. Thus the use of
function generally results in a shorter, less expensive program that is quicker
to write and easier to debug.
A function is a
self-contained program segment that carries out some specific, well defined
task. Every C program consists of one or more functions. One of these functions
must be called main. Execution of the program will always begin by carrying out
the instructions in main. Additional functions will be subordinate to main, and
perhaps to one another.
A function will
carry out its intended action whenever it is accessed from some other portion
of the program. The same function can be accessed from several different places
within a program. Once the function has carried out its intended action,
control will be returned to the point from which the function was accessed.
Generally, a
function will process information that is passed to it from the calling portion
of the program and return a single value. Information is passed to the function
via special identifiers called arguments (also called parameters), and returned
via the return statement. Some functions, however, accept information but do
not return anything, whereas, some function might accept nothing and return
something.
Advantages of using Function
- C programs can be modularized through the intelligent
use of functions, which allows a large program to be broken down into a
number of smaller, self-contained components, each of which has some
unique, identifiable purpose.
- The use of a function avoids the need for redundant
programming of the same instructions.
- Logical clarity is achieved from the decomposition of
a program into several concise functions, where each function represents
some well-defined part of the overall problem.
- The use of functions also enables a programmer to
build a customized library of frequently used routines.
The execution of any C program starts from the main
(). There are two kinds of functions.
Library Function and User Defined Function
Library
Function
Library functions are not written by
us. Its definition is written in library file and its prototype is defined in
header file. printf () and scanf () are an example of library function. Other
library functions are sqrt (), pow () etc.
User
Defined function
C provides capability to define
function by the programmer according to their requirement. These functions are
called User defined functions. User defined function is self contained block of
code that performs a particular task. Once a user defined function has been written,
it can be treated as a block that can be called from other part of the program.
A function consists of three parts:
i. Function prototype/function declaration
ii. Function definition
iii. Function Call
Function Prototype/Function declaration
Function prototype tells the compilers how
the function will look in terms of its name, the data type it returns and
number of parameters it takes.
Syntax:
return type name of the function (data type
arg 1, data type arg 2, data type arg n);
(We should note that argument name in
function declaration is optional)
Function Definition
Function
definition contains programming statements or codes to perform the specific
task. Function definition is executed only if it is called.
Function
Call
A function can
be called by specifying its name, followed by a list of arguments enclosed in
parentheses and separated by commas. If the function call does not require any
arguments, an empty pair of parentheses must follow the name of the function.
The function call may be a part of a simple expression (such as assignment
statement), or it may be one of the operands within a more complex expression.
Note: In
C practice of following function declaration by function definition is very
common. Either method is correct, we can declare the function first, write the
main function then define the function, or declare and define the function and
write the main function.
To clarify the need for
user defined function, let us write a program to print a program to output as
given below.
***************************
Welcome
to St. Xavier’s Campus
***************************
C Programming
***************************
I am learning C function
***************************
Example #1
#include<stdio.h>
#include<conio.h>
void main()
{
printf("********************************");
printf("\n\t
Welcome to St. Xavier's Campus\n");
printf("********************************");
printf("\n\t
C Programming\n");
printf("********************************");
printf("\n\t
I am learning C function\n");
printf("********************************");
getch();
}
Example #2
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
for(i=0;i<50;i++)
printf("*");
printf("\n\t Welcome to St. Xavier's
Campus\n");
for(i=0;i<50;i++)
printf("*");
printf("\n\t C Programming\n");
for(i=0;i<50;i++)
printf("*");
printf("\n\t I am learning C
function\n");
for(i=0;i<50;i++)
printf("*");
getch();
}
Example:
#include<stdio.h>
#include<conio.h>
void
asterisks_line();
// function declaration
void main
()
{
clrscr();
asterisks_line(); // calling function
printf("\n\t Welcome to St. Xavier's
Campus\n");
asterisks_line(); // calling function
printf("\n\t C Programming\n");
asterisks_line(); // calling function
printf("\n\t I am learning C
function\n");
asterisks_line(); // calling function
getch();
}
void asterisks_line() // called function
{
int i;
for(i=0;i<50;i++)
printf("*");
}
//declaring the function and defining
the function at the same time
#include<stdio.h>
#include<conio.h>
float
calarea(float a, float b) //function
declaration
{
float area;
area=l*b; //function definition
return area;
}
void main()
{
float l, b, area;
clrscr();
printf("\n Enter length and breadth
of the rectangle:");
scanf("%f %f", &l, &b);
area=calarea(l, b); //function call
printf("\n Area of the rectangle is
:%f", area);
getch();
}
Types
of User Defined Function
Function can be
classified into four categories based on the passing of the argument to the
function and returning of the value from the function.
i. Function
with no arguments and no return value
ii. Function
with arguments and no return value
iii. Function
with no arguments and return value
iv. Functions
with arguments and return value
//Program to calculate area of a circle using function with no
arguments and no return value
#include<stdio.h>
#include<conio.h>
void
calarea()
{
float r, area;
printf("\n Enter radius of the
circle:");
scanf("%f", &r);
area=3.1412*r*r;
printf("\n Area of the circle: %f",
area);
}
void main()
{
calarea();
getch();
}
//Program to calculate area of circle using function that takes
argument but returns nothing
#include<stdio.h>
#include<conio.h>
void calarea(float
r)
{
float area;
area=3.1412*r*r;
printf("\n Area of the circle: %f",
area);
}
void main()
{
float r;
printf("\n Enter radius of the
circle:");
scanf("%f", &r);
calarea(r);
getch();
}
//Program to calculate area of circle using function that takes no
argument but return some value.
#include<stdio.h>
#include<conio.h>
float
calarea()
{
float r, area;
printf("\n Enter radius of the
circle:");
scanf("%f", &r);
area=3.1412*radius*radius;
return area;
}
void main()
{
float area;
area= calarea();
printf("\n Area of circle:%f",
area);
getch ();
}
//Program to calculate area of circle using function that takes some
arguments and return some value.
#include<stdio.h>
#include<conio.h>
float
calarea(float r)
{
float area;
area=3.1412*radius*radius;
return area;
}
void main()
{
float r,area;
printf("\n Enter radius of the
circle:");
scanf("%f", &r);
area=calarea(r);
printf("\n Area of circle:%f",
area);
getch();
}
Local and Global variable:-
Local variable:
Variable
declared within functions is called local variable. Its name and value are
valid only within the function in which it is declared.
// program to show the use of local variable
#include<stdio.h>
#include<conio.h>
int
get_data();
void main()
{
int num;
num=get_data();
printf(“\n The
number is %d”, num);
getch ();
}
int
get_data()
{
int n;
printf(“Enter
a number:\n”);
scanf(“%d”,
&n);
return n;
}
Output:
Enter a
number
125
The number
is 125
Global Variable:-
A global
variable is a variable whose name, value and existence are known throughout the
execution of the program. It is accessible to all the functions defined in the
program. It is declared at the beginning of the program, before the definition
of the main () function.
// use of the global variable
#include<stdio.h>
#include<conio.h>
int
length,width,area;
int get_data();
void
calc_area();
void main()
{
printf(“Enter
the length:\n”);
length=get_data();
printf(“Enter
the width :\n”);
width=get_data();
calc_area();
printf(“\n The
area is %d\n”, area);
getch();
}
int get_data()
{
int a;
scanf(“%d”,
&a);
return a;
}
void
calc_area()
{
area=length*width;
}
Recursion
A recursive
function is a function that calls itself to perform a specific operation. The
process of a function calling itself is called recursion.
// program to calculate factorial of number using recursive method
#include<stdio.h>
#include<conio.h>
int
fact_recur(int);
void main()
{
int n,
result;
printf(“Enter
a number:\n);
scanf(“%d”,&n);
result= fact_recur
(n);
printf(“The
factorial of %d is %d”, n, result);
getch();
}
int
fact_recur(int n)
{
if(n==0)
return 1;
else
return
(n*fact_recur(n-1));
}
Storage Classes
The storage
class precedes the variables declaration and tells the compiler how the
variable should be stored. Generally supported storage classes are:
·
auto
·
static
If the storage
class in the variable declaration is omitted, it is assumed of type auto i.e.
storage class is auto by default.
#Auto storage class:-
If not
initialized in the declaration statement their initial value is unpredictable
which is often called garbage value. If the variable is declared within a
function, then only it is visible to that function. But if it is declared
outside the function, then it is visible to all the function. If retains its
value till the control remains in the block in which the variable is declared.
e.g.
{
auto int
i,j=10;
printf(“\n
Value of i=%d\n value of j=%d”,I,j);
}
Output:
Value of
i=1250
Value of
j=10
Next time when
we run this program, we get different value of I as I is not initialized. So,
it is assigned by any garbage value.
//Program to show the auto storage class variable is declared outside
all blocks.
{
auto int
j=10;
{
printf(“\n
Value of j is %d”, j);
printf(“\n
value of j is %d”, j);
}
}
//program to show the auto storage class when same variable is declared
in different blocks
{
auto int j=10;
{
{
auto int j=50;
printf (“\n Value of auto
variable %d”, j);
}
printf(“\n value of j is %d”, j);
}
}
Note that the
compiler treats this j as different variable since they are defined in
different blocks although within the same function. As the inner block is
complete, the variable j loses its value 50 and in outer loop, variable j
refers to value 10.
Static storage class:-
If it is not
initialized in the declaration statement, their initial value is zero. If the
variable is declared outside the function, then it is visible to all the
functions.
It retains its
value between different function calls.
//program to show the use of static storage class
#include<stdio.h>
void increment();
void main()
{
increment();
increment();
increment();
}
void increment()
{
auto
int i=1;
printf(“%d”,
i);
i++;
}
Output:
1 1 1
#include<stdio.h>
void increment();
void main()
{
increment();
increment();
increment();
}
void increment()
{
static
int i=1;
printf(“%d”,
i);
i++;
}
Output: 1 2 3
In 1, when
control comes out of function definition, the memory location held by it will
be destroyed and it forgets the previous value. When again enters, I
reinitialized to 1.
In 2, each time
the control comes out of function, it retains the previous value since the
integer variable I is declared as static.
Function and Arrays
In C, it is
possible to pass the value of an array element and even an entire array as an
argument t a function. To pass a single array element to a function, the array
element is specified as an argument to the function in normal fashion.
// program to show array element as argument to function
#include<stdio.h>
void
print_age(int);
void main()
{
int age[]={120,18,35,19,27},i;
for(i=0;i<5;i++)
print_age(age[i]);
}
void
print_age(int a)
{
printf(“%2d”,a);
}
Output:
120 18 35
19 27
//program to pass the entire one dimensional array to function
#include<stdio.h>
void main()
{
int
age[]={20,18,25,19,27},i;
print_age(age);
}
void
print_age(int age[])
{
int i;
for(i=0;i<5;i++)
{
printf(”%4d”,age[i]);
}
}
0 Comments
Please Don't Post Spam Links Under Comment Section.