Вы находитесь на странице: 1из 16

FUNCTIONS

Def: A function is self contained block of statements that performs a


particular task.
C functions are divided into two parts
c) Pre-defined functions(library functions)
d) User-defined functions
The difference between these two categories is that library functions
are not required to be written by us where as user define function has to be
developed by the user at the time of writing program.
In order to make use of user defined function, we need to establish
three elements that are related to function.
e) Function declaration
f) Function definition
g) Function call
FUNCTION DECLARATION:
Like variables all functions in a c program must be declared, before
they are invoked. A function declaration(also known as function prototype)
consists of four parts.
h) Function type(return type)
i) Function name
j) Parameter List
k) Terminating semicolon.
The general format is
function_type function_name(parameter list);
Example: void display(void);
int square(int m);
int mul(int m, int n);
When a function does not take any parameter list and does not return
any value, its prototype is written as
void display(void);
Equally acceptable forms of declarations of mul function
int mul(int, int);
mul(int a, int b); (default return type in c is int)
mul(int,int);
A prototype declaration may be placed in two places in a program
1) Above all the functions (including main)
2) Inside a function definition.
When we place the declaration above all the functions (in the global
declaration section), the prototype is referred to as a global prototype.
Such declrations are available for all the functions in the program.
When we place it in a function definition (in the local declaration
section), this prototype is called local prototype.
DEFINITION OF FUNCTION:
A function definition, also known as function
implementation.
A general format of function def is
function_type fuction_name(parameter list)
{
Local variable declarations;
stmt 1;
stmt 2;
--------
----------
return statement;
}
The first line
function_type function_name(parameter list)
is known as function header and the staments with in the openings
and closing braces constitutes the function body which is a compound
statement.
FUNCTION HEADER
The function header consists of three parts the function type (return
type), the function name and the formal parameter list. Note that semicolon
is not used at the end of the function header.

NAME AND TYPE


The function type specifies the type of value(like float int or double)
that the function is expected to return to the program calling the function.
If the return type is not explicitly specified, C will assume that it is an
integer type. If the function is not returning any thing we need to write
void.
The function name is any valid C identifier. The name should be
appropriate to the task performed by the function. Additional care must be
taken to avoid duplicating library function names.
FORMAL PARAMETRE LIST:
The parameter list declares the variables that will be receive the
data sent by the calling program. They serve as input data to the function to
carry out the specific task. These parameters are also known as formal
parameters list.
Ex: float mul(float x, float y)
{
---------
---------
}
int sum(int a,b) is illigel.
FUNCTION BODY:
The function body contains the declarations and statements
necessary for performing the required task.
Local declarations that specify the variable needed by the function.
l) Function statements that performs the task of the function.
m) A return statement that returns the value evaluated the
function.
If a function does not return any value we can omit the return
statement. However note that the return type should be specified as void.
When a function reaches its return statement, the control is
transferred back to the calling function. In the absence of return
statement, the closing brace acts as void return.
FUNCTION CALL:
A function can be called by simply using the function name
followed by a list of parameters (actual parameters), if any, enclosed in
parenthesis.
When the compiler encounters a function call the control is
transferred to the function definition. The function is executed line by line
as described and a value is returned when a return statement is
encountered.
EXAMPLE:
void printline(void); /*Declaration*/
main()
{
printline();/* Function calling*/
printf(“Welcome to C\n”);
printline();
}
void printline() /*Funciton definition */
{
int i;
for(i=0;i<40;i++)
printf(“-“);
printf(“\n”);
}

The above program contains two user-defined function


main() function
printline() function
The program execution begin with main function. During execution of the
main function, the first statement is
printline()
which indicates that the function printline is to be executed? At this point,
the program control is transferred to the function printline. After
executing the printline function, which output a line of 40 character length,
the control is again back to main. Now, the execution continues at the point
when the function call was executed. After executing the printf statement,
the control is again transferred to the printline function for printing the line
once more.
The main function calls the user defined printline function two times
and the library function one time. Notice that printline function itself calls
the library function 40 times repeatedly.
RETURN VALUES AND THEIR TYPES
A function may or may not send back any value to the calling function. If
it does, it is done through through return statement. While it is possible to
pass to the called function any number of values the called function can only
return one value per call, at the most.
The return statement can take one of the following forms
return;
or
return(expression);
The first one does not return any value; it acts much as closing brace
of the function. When a return is encountered, the control is immediately
passed back to the calling function. An example of the use of a simple return
is as follows
if(error)
return;
The second form of the return with an expression returns the value
of the expression. For example the function
int mul(int x,int y)
{
int p;
p=x*y;
return(p);
}
returns the value of the p which is the product of the values of x and
y. The last two statements can be combined into one statement as follows.
return(x*y);

A function may have more than one return statement this situation
arises when the value returned is based on certain conditions. For example
if(x<=0)
return(0);
else
return(1);
If the function having two return statements also but it returns only
one value at a time.
The user define function may be classified as three ways based on the
formal arguments passed and return type
1) Functions with no arguments and no return value
A function is invoked without passing any formal arguments
from the calling portion of a program and also the calling function
does not return any value to the called function.

#include<stdio.h>
void display();
main()
{
void display();
}
void display()
{
printf(“Hello\n”);
printf(“How r u”);
}

OUTPUT: Hello
How r u
2) Functions with arguments and no return values
This type of function passes some formal arguments to a function but
the function does not return any value to the caller function.

#include<stdio.h>
#include<conio.h>
void square(int);
void main()
{
int n;
clrscr();
printf(“Enter a value\n”);
scanf(“%d”,&n);
square(n);
getch();
}
void square(int x)
{
int s;
s=x*x;
printf(“The square of %d is %d”,x,p);
}

3) Function with arguments and return value

The third type of function passes some formal arguments to a


function from a calling portion of the program and the called function
returns value back to the caller function.
#include<stdio.h>
#include<conio.h>
int mul(int,int)
void main()
{
int a,b,c;
clrscr();
printf(“Enter two no’s\n”);
scanf(“%d %d”,&a,&b);
c=mul(a,b);
printf(“Product of %d and %d is %d”,a,b,c);
getch();
}
int mul(int x,int y)
{
int p;
p=x*y;
return(p);
}
RECURSION:
Recursion is a process by which a function calls itself repeatedly until
some specified condition has been satisfied. This process is used for
repetitive computations in which each action is stated in terms of previous
result.
In order to solve a problem recursively, two conditions must be
satisfied. First the problem must be written in a recursive form and second
the problem statement must include a stopping condition.
A function is said to be recursive function if it calls itself.
#include<stdio.h>
#include<conio.h>
long fact(int);
void main()
{
long a;
int n;
clrscr();
printf("Enter the no\n");
scanf("%d",&n);
a=fact(n);
printf("Factorial of %d = %d",n,a);
getch();
}
long fact(int x)
{
long i;
if(x==1)
return(1);
else
i=x*fact(x-1);
return(i);
}

STORAGE CLASSES IN C:
To fully define a variable one needs to mention not only its ‘type’ but
also its ‘storage class’. In other words, not only do all variables have a data
type, they also have a storage class.
A variable’s storage class tells us:
1) Where the variable would be stored (either in memory or registers)
2) What will be the initial value of the variable, if initial value is not
specifically assigned (i.e. the default initial value).
3) What is the scope of the variable; i.e. in which functions the value of the
variable would be available.
4) What is the life of the variable i.e. how long would the variable exist.
There are four storage classes in C:
n) Automatic Storage Class
o) Register Storage Class
p) Static Storage Class
d)External Storage Class

Automatic Storage Class:


The features of a variable defined to have an automatic storage class
are as under:
Storage -- Memory
Default Initial value -- Garbage value
Scope -- Local to the block in which the variable
is defined
Life -- Till the control remains within
the block in which the variable is
defined
Following program shows how an automatic storage class variable is
declared, and the fact that if the variable is not initialized it contains a
garbage value.
main()
{
auto int i,j;
printf(“%d %d”,i,j);
}
OUTPUT: 5657,3653
Where 5657 and 3653 are garbage values of i and j. When you run
this program u may get different values, since garbage values are
unpredictable. So always make it a point that initialize the automatic variable
properly, otherwise we get unpredictable results. Note that keyword for
the storage class is auto, and not automatic. Scope and life of an automatic
variable is illustrated in the following program
main()
{
auto int i=1;
{
{
{
printf(“\n%d”,i); OUTPUT: 1 1 1
}
printf(“\n%d”,i);
}
printf(“\n%d”,i);
}
}
This is because all printf() statements occur within the outermost
block ( a block is all statements enclosed within a pair of braces) in which i is
defined. The moment the control comes out of the block in which the
variable is defined, the variable and its value is lost.
main()
{
auto int i=1;
{
auto int i=2;
{
auto int i=3;
printf(“\n%d”,i);
}
printf(“\n%d”,i);
}
printf(“\n%d”,i);
}
OUTPUT: 321
Note that the compiler treats the three i’s as totally different
variables, since they are defined in different blocks. Once the control comes
out of the innermost block the variable i with value 3 is lost, and hence the i
in the second printf() refers to i with value 2. Similarly, when the control
comes out of the next innermost block, the third printf() refers to the i
with value 1.
Register Storage Class:
The features of a variable defined to be of register storage class
are as under
Storage -- CPU registers
Default Initial value -- Garbage value
Scope -- Local to the block in which the
variable is defined
Life -- Till the control remains within the
block in which the variable is
defined.
A value stored in a CPU register can always be accessed faster than
the one that is stored in memory. Therefore, if a variable is used at many
places in a program it is better to declare its storage class as register. A
good example of frequently used variable is loop counters.
main()
{
register int i;
for(i=0;i<=10;i++)
printf(“\n%d”,i);
}
Here, even though we have declared the storage class of i as register,
we cannot say for sure that the value of i would be stored in a CPU register.
Why? Because the number of CPU registers are limited, and they may be
busy doing some other task. In such an event… variable works as if its
storage class is auto.
Static Storage Class:
The features of a variable defined to be of register storage class are
as follows
Storage -- Memory
Default Initial value -- Zero
Scope -- Local to the block in which the
variable is defined
Life -- Value of the variable persists
between different function calls
The program above consist of two functions main() and increment(). The
function increment() gets called from main() thrice. Each time it increments
the value of i and prints it. The only difference in the two programs is that
one uses auto storage class for variable i, whereas the other uses static
storage class. Like auto variables, static variables are also local to the block
in which the variable declared. The difference between them is that static
variables don’t disappear when the function is no longer active. Their
value persists. If the control comes back to the same function again the
static variables have the same values they had last time around.
In the above example, when variable i is auto, each time increment ()
is called it is re-initialized to one. When the function terminates, i vanishes
and its new value of 2 is lost. The result no matter how many times we call
increment(), i is initialized to 1 every time.

On the other hand, if i is static, it is initialized to 1 only once. It is


never initialized again. During the first call to increment(), i is incremented
to 2. Because i is static, this value persists. The next time increment() is
called, i is not re-initialized to 1; on the contrary its old value 2 is still
available. This current value of i(i.e. 2 ) gets printed and then i=i+1 adds 1 to
i to get value of 3. When increment() is called the third time, the current
value of i (i.e.) gets printed and once again i is incremented. In short, if the
storage class is static then the statement static int i=1 is executed only
once, irrespective of how many times the same function is called.
include<stdio.h> #include<stdio.h>
void increment(); void increment();
main() main()
{ {
increment(); increment();
increment(); increment();
increment(); increment();
} }
void increment() void increment()
{ {
auto int i=1; static int i=1;
printf(“%d\t”,i); printf(“%d\t”,i);
i=i+1; i=i+1;
} }
OUTPUT: 1 OUTPUT: 1
1 2
1 3

External Storage Class:


The features of a variable whose storage class has been defined as
external are as follows:
Storage -- Memory
Default Initial value -- Zero
Scope -- Global
Life -- As long as the program’s
execution doesn’t
come to end.
External variables differ from those we have already discussed in
that their scope is global, not local. External variables are declared outside
all functions, yet are available to all functions that care to use them. Here is
an example to illustrate this fact
Example:
int i=0;
main()
{
printf(“\t i= %d”,i);
increment();
increment();
decrement();
decrement();
}
void increment()
{
i=i+1;
printf(“\t %d”,i);
}
void decrement()
{
i=i-1;
printf(“\t%d”,i);
}

OUTPUT: i=0 i=1 i=2 i=1 i=0


As is obvious from the above output, the value of i is available to the
function increment() and decrement() since i has been declared outside all
functions.
int x=10;
main()
{
int x=20;
printf(“\n%d”,c);
display();
}
display()
{
printf(“\n%d”,x);
}
Here x is defined at two places, once outside main() and once inside it.
When the control reaches the printf() in main() which x gets printed?
Whenever such a conflict arises, it’s the local variable that gets preference
over the global variable. Hence the printf() there is no such conflict. Hence
this time the value of the global x, i.e. 10 gets printed.

MATH LIBRARY FUNCIONS


Math library functions allow the programmer to perform common
mathematical caluculations.
Some C math library functions are
Function Description Example
sqrt(x) square root of x sqrt(9.000) is 3.00
exp(x) Exponential function ex exp(1.0) is 2.718282
log(x) Natural logarithm of x(base e) log(2.7182) is 1.0
log10(x) logarithm of x(base 10) log10(1.0) is 0.0
fabs(x) absolute value of x fabs(5.0) is 5.0
ceil(x) rounds x to the smallest integer ceil(9.2) is 10.0
not less than x
floor(x) rounds x to the largest integer floor(9.2) is 9.0
not greater than x
pow(x,y) x raised to power y pow(2,7) is 128.0
sin(x) trigonometric sine of x sin(0.0) is 0
(x in radians)
cos(x) trigonometric cosine of x cos(0.0) is 1
(x in radians)
tan(x) trigonometric tangent of x tan(0.0) is 0.0
(x in radians)

RANDOM NUMBER GENERATION:


C provides a special function called rand( ) which is to generate
numbers randomly. This function generates an integer between 0 and
Rand_Max. The standard states that the Rand_max value must be atleast
32767. This function is defined in <stdlib.h> header file.
Example:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int i,n;
clrscr();
for(i=0;i<5;i++)
{
n=rand();
printf("\t%d",n);
}
getch();
}
OUTPUT: 4894 2762 76 3338 2323
If we execute the program every time we will get same output. To
produce a different sequence of random numbers for each execution c
provides another function called srand( ). This is also defined in stdlib.h
header file. Function srand takes an unsigned integer argument and seeds
function rand to produce a different sequence of random numbers for each
execution of the program.
The use of srand is demonstrated in the following program. Function
srand takes an unsigned value as an argument.
Example:
#include<stdlib.h>
void main()
{
int i,n;
unsigned seed;
printf("Enter seed:\n");
scanf("%u",&seed);
srand(seed);
for(i=0;i<5;i++)
{
n=rand();
printf("%d\t",n);
}
}
OUTPUT: Enter seed
20
2839 944 4563 9837 8282
Enter seed
40
276 1 27298 26112 622
Let us run the program observer the results. Notice that a
different sequence of random numbers is obtained each time the program is
run, provided that a different seed is supplied.
If we wish to randomize without the need for entering a seed each
time, we may use a statement like
srand(time(NULL));
This causes the computer read its clock to obtain the value for the seed
automatically. Function time returns the current time of day in seconds. This
value is converted to an unsigned integer and used as the seed to the random
number generator.
RECURSION VS ITERATION
Both iteration and recursion are based on a control structure:
Iteration uses a repetition structure: recursion uses a selection structure.
Both iteration and recursion involve repetition. Iteration explicitly uses a
repetition structure: recursion achieves repetition through repeated
function calls. Iteration and recursion each involve a termination test:
Iteration terminates when the a loop-continuation condition fails; recursion
terminates when a base case is recognized. Iteration with counter-
controlled repetition and recursion each gradually approach termination:
Iteration keeps modifying a counter until the counter assumes a value that
makes the loop-continuation condition fail. Recursion keeps producing simpler
versions of original problem until the base case is reached. Both iteration
and recursion can occur infinitely: An infinite loop occurs with iteration if
the loop-continuation test never becomes false; infinite recursion occurs if
the recursion step does not reduce the problem each time in a manner that
converges on the base case.
Recursion has many negatives. It repeatedly invokes the mechanism,
and consequently the overhead, of function calls. This can be expensive in
both processor time and memory space. Each recursive call causes another
copy of the function (actually only the function’s variables) to be created:
this can consume considerable memory. Iteration normally occurs within a
function so the overhead of repeated function calls and extra memory
assignment is omitted.

Вам также может понравиться