FUNCTIONS
Introduction-Modular
Programming
The decomposition of a program into
individual program modules is generally
considered to be an important part of good
programming.
The use of functions allows a large program
to be broken down into a number of
smaller, self-contained components, each
of which has some unique, identifiable
purpose. Thus a C program can be
modularized through the intelligent use of
such functions.
Modular Programming
Cont…
Many programs require a particular group of
instructions to be accessed repeatedly from several
different places within a program.
The repeated instruction can be placed within a
single function, which can then be accessed
whenever it is needed.
Thus, the use of a function avoids the need for
redundant (repeating) programming of the same
instructions.
The decomposition of a program into individual
program modules is generally considered to be an
important part of good programming.
Function
function is a self-contained program
segment that carries out some specific
well-defined task.
Every C program consists of one or more
functions.
The most important function is main.
The definitions of functions may appear in
any order in a program file because they
are independent of one another.
A function can be executed from anywhere
within a program.
Once the function has been executed,
Functions contains special identifiers called
parameters or arguments through which
information is passed to the function and
from functions information is returned via
the return statement.
It is not necessary that every function must
return information, there are some
functions also which do not return any
information
Functions Types
Built in Functions
User Defined Functions
Built in Functions
The standard library functions are in-
built functions in C programming to
handle tasks such as mathematical
computations, I/O processing, string
handling etc.
These functions are defined in the
header file. When you include the
header file, these functions are
available for use. For example:
The printf() is a standard library function to
send formatted output to the screen
(display output on the screen). This
function is defined in "stdio.h" header file.
There are other numerous library functions
defined under "stdio.h", such as scanf(),
fprintf(), getchar() etc. Once you include
"stdio.h" in your program, all these
functions are available for use.
User Defined Functions
C language allows programmer to define
functions. Such functions created by the
user are called user-defined functions.
Depending upon the complexity and
requirement of the program, you can create
as many user-defined functions as you
want.
Properties of a Function
Every function has a unique name.
A function is independent and it can
perform its task without intervention from
or interfering with other parts of the
program.
A function returns a value to the calling
program.
This is optional and depends upon the task
your function is going to accomplish.
Function Declaration
A function declaration tells the compiler about a
function's name, return type, and parameters.
The actual body of the function can be defined
separately.
A function declaration has the following parts −
return_type function_name( parameter list );
For the above defined function max(), the function
declaration is as follows −
int max(int num1, int num2);
Parameter names are not important in function
declaration only their type is required, so the
following is also a valid declaration −
int max(int, int);
Function Definition
A function definition provides the actual
body of the function.
Function definition has three principal
components: the first line, the parameter
declarations and the body of the functions.
How does a Function
Work?
A function has
Return Type
Function Name
Parameter List
Function Body
return-type
return type specifies the type of
value(int,float,char,double) that function is
expected to return to the program calling
the function.
function-name
function name specifies the name of the
function. The function name is any valid C
identifier
parameter-list
The parameter list declares the variables
that will receive the data sent by calling
program.
They often referred to as formal parameters.
Function body
The function body contains the declarations
and the statement(algorithm) necessary for
performing the required task.
The body is enclosed within curly braces { }
Function Arguments/Parameters
If a function is to use arguments, it must
declare variables that accept the values of
the arguments.
These variables are called the formal
parameters of the function.
Formal parameters behave like other local
variables inside the function and are
created upon entry into the function and
destroyed upon exit.
While calling a function, there are two ways
in which arguments can be passed to a
function −
Actual parameters and formal parameters
There are two other categories that you should
know about that are also referred to as
"parameters". They are called "parameters"
because they define information that is passed to
a function.
Actual parameters are parameters as they appear
in function calls i.e. it is present in calling function.
Formal parameters are parameters as they
appear in function declarations i.e. it appears in
called function.
Example:
void main()
{
int num1;
display(num1);
}
void display(int para1)
{
-----------
-----------
}
para1 is “Formal Parameter“
num1 is “Actual Parameter“
Calling a Function
While creating a C function, you give a
definition of what the function has to do.
To use a function, you will have to call that
function to perform the defined task.
When a program calls a function, the
program control is transferred to the called
function.
A called function performs a defined task
and when its return statement is executed
or when its function-ending closing brace is
reached, it returns the program control
back to the main program.
Calling a Function
#include <stdio.h>
int max(int num1, int num2);
void main (){
int a, b,ret;
clrscr();
printf("Enter two Numbers\n");
scanf("%d%d",&a,&b);
ret = max(a, b);
printf( "Max value is : %d\n", ret );
getch();
}
int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else result = num2;
return result; }
Calling a Function
#include<stdio.h>
int sum();
void main()
{
printf("Going to calculate the area of the square\
n");
float area = square();
printf("The area of the square: %f\n",area);
}
int square()
{
float side;
printf("Enter the length of the side in meters: ");
scanf("%f",&side);
return side * side;
}
Prime number using function
#include<stdio.h>
int check_prime(int);
void main() {
int n, result;
clrscr();
printf("Enter an integer to check whether it is prime or not.\n");
scanf("%d",&n);
result = check_prime(n);
if ( result == 1 )
printf("%d is prime.\n", n);
else
printf("%d is not prime.\n", n);
getch(); }
int check_prime(int a) {
int c;
for ( c = 2 ; c <= a - 1 ; c++ ) {
if ( a%c == 0 )
return 0; }
return 1; }
Call by value
This method copies the actual value of an argument
into the formal parameter of the function.
In this case, changes made to the parameter inside
the function have no effect on the argument.
Call by reference
This method copies the address of an argument into
the formal parameter.
Inside the function, the address is used to access
the actual argument used in the call.
This means that changes made to the parameter
affect the argument.
Call by value in C
In call by value, original value is not modified.
In call by value, value being passed to the function is
locally stored by the function parameter in stack
memory location.
If you change the value of function parameter, it is
changed for the current function only.
It will not change the value of variable inside the caller
method such as main().
While Passing Parameters using call by value , xerox
copy of original parameter is created and passed
to the called function.
Any update made inside method will not affect the
original value of variable in calling function.
Example
void change(int num) {
printf("Before adding value inside function num=
%d \n",num);
num=num+100;
printf("After adding value inside function num=
%d \n", num);
}
void main() {
int x=100;
clrscr();
printf("Before function call x=%d \n", x);
change(x);//passing value in function
printf("After function call x=%d \n", x);
getch();
Call by Value Example: Swapping the values of the two
variables
#include <stdio.h>
void swap(int , int); //prototype of the function
int main() {
int a,b;
printf("Enter two Numbers\n");
scanf("%d%d",&a,&b);
printf("Before swapping the values in main a = %d, b = %d\
n",a,b);
swap(a,b);
printf("After swapping values in main a = %d, b = %d\n",a,b);
}
void swap (int a, int b) {
int temp;
temp = a;
a=b;
b=temp;
Call by reference in C
In call by reference, original value is modified
because we pass reference (address).
Here, address of the value is passed in the
function, so actual and formal arguments
shares the same address space.
Hence, value changed inside the function, is
reflected inside as well as outside the function.
While passing parameter using call by address
scheme , we are passing the actual address
of the variable to the called function.
Any updates made inside the called function
will modify the original copy since we are
directly modifying the content of the exact
memory location.
Example
void change(int *num) {
printf("Before adding value inside function nu
m=%d \n",*num);
(*num) += 100;
printf("After adding value inside function num
=%d \n", *num);
}
void main() {
int x=100;
clrscr();
printf("Before function call x=%d \n", x);
change(&x);//passing reference in function
printf("After function call x=%d \n", x);
getch();
Call by reference : Swapping the values of the two variables
#include <stdio.h>
void swap(int *, int *); //prototype of the function
int main()
{
int a,b;
printf("Enter two Numbers\n");
scanf("%d%d",&a,&b);
printf("Before swapping the values in main a = %d, b = %d\n",a,b);
swap(&a,&b);
printf("After swapping values in main a = %d, b = %d\n",a,b);
}
void swap (int *a, int *b)
{
int temp;
temp = *a;
*a=*b;
*b=temp;
printf("After swapping values in function a = %d, b = %d\n",*a,*b);
}
Call by Value Vs Call by Reference
No. Call by value Call by reference
1 A copy of value is passed to the An address of value is passed to
function the function
2 Changes made inside the Changes made inside the function
function is not reflected on is reflected outside the function
other functions also
3 Actual and formal arguments Actual and formal arguments will
will be created in different be created in same memory
memory location location
NESTING OF FUNCTIONS
C language also allows nesting of functions, one
function using another function inside its body. We
must be careful while using nested functions,
because it may lead to infinte nesting.
Syntax:
function1()
{
function2() ; //statements
}
If function2 calls function1 inside it, then in this case it
will lead to infinite nesting, they will keep calling
each other. Hence we must be careful.
Example:
#include<stdio.h>
#include<conio.h>
void fun2()
{
printf("\n Statement 2");
}
void fun1()
{
printf("\n Statement 1");
fun2();
}
void main()
{
clrscr();
fun1();
printf("\n Statement 3");
getch();
}
Output:
Statement1
Statement2
Statement3
Recursion
Recursion is the process of repeating items
in a self-similar way.
In programming languages, if a program
allows you to call a function inside the
same function, then it is called a recursive
call of the function.
Syntax:
void recursion()
{
recursion(); /* function calls itself */
}
void main()
{
recursion();
}
Factorial of a number using
recursion
#include<stdio.h>
#include<conio.h> int factorial(int x)
int factorial(int x); {
void main() int r=1;
{ if(x==1)
int a,b; return 1;
clrscr(); else
printf("Enter no."); r=x*factorial(x-1);
scanf("%d",&a); return r;
b=factorial(a); }
printf("%d",b);
getch();
}
#include <stdio.h>
int f(int);
int main()
{
int n, c = 0, i;
printf("Enter a number");
scanf("%d", &n);
printf("Fibonacci series terms are:\n");
for (i = 1; i <= n; i++)
{
printf("%d\n", f(c));
c++;
}
return 0;
}
int f(int n)
{
if (n == 0 || n == 1)
return n;
else
return (f(n-1) + f(n-2));
}
Advantages of Recursion
Avoidance of unnecessary calling of
functions.
A substitute for iteration where the
iterative solution is very complex.
For example to reduce the code size for
Tower of Honai application, a recursive
function is best suited.
Disadvantages of Recursion
A recursive function is often confusing.
The exit point must be explicitly coded.
Recursion takes a lot of stack space,
usually not considerable when the program
is small and running on a PC.
Recursion uses more processor time.