0% found this document useful (0 votes)
4 views

Function Of C

The document provides an overview of functions in C programming, detailing their definitions, classifications, and advantages. It explains the differences between library functions and user-defined functions, as well as the importance of function declaration, definition, and parameter passing. Additionally, it covers storage classes, variable scope, and visibility within C programs.

Uploaded by

nitinchavda2615
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Function Of C

The document provides an overview of functions in C programming, detailing their definitions, classifications, and advantages. It explains the differences between library functions and user-defined functions, as well as the importance of function declaration, definition, and parameter passing. Additionally, it covers storage classes, variable scope, and visibility within C programs.

Uploaded by

nitinchavda2615
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

TOPICS

1 Functions: Definition, Syntax, Terminology


2 Function Declaration, Classification (Arguments and Return Type)
3 Storage Classes, Sample C Programs
------------------
Functions
Functions are building blocks of a C program. Understanding functions is one of the most
important steps in C language.
Definition
A function is a self-contained program segment that carries out a specific, well-defined
task. A function is a collection of instructions that performs a specific task. Every function
is given a name. The name of the function is used to invoke (call) the function. A
function may also take parameters (arguments). If a function takes parameters, parameters
are to be passed within parentheses at the time of invoking function.
A function theoretically also returns a value, but you can ignore the return value of the
function in C language. Function name must follow the same rules of formation as other
variables in C. The argument list contains valid variable names separated by commas.
C is a function-oriented language. Many operations in C language are done through
functions. For example, we have used printf() function to display values, scanf() function
to read values from keyboard, strlen() function to get the length of the string etc.
Classification of Functions
C functions can be classified into two categories namely
 Library functions
 User defined functions.
The main difference between these 2 categories is that
 library functions are not required to be written by the user, printf, scanf, strlen, sqrt
and pow, etc belong to the category of library functions.
 user defined function has to be developed by the user at the time of writing a
program. main() function is an example of user-defined function. Every program
must have a main function to indicate where the program has to begin its
execution.
Standard/Library functions
A function which is made available to programmer by compiler is called as
standard or pre-defined function. Every C compiler provides good number of

Prepared by : Prof. Jahnavi Shukla Page 112


Problem Solving using C Language ( PS C )

functions. All that a programmer has to do is use them straight away. For
example, if you have to find length of a string , use strlen() without having to
write the required code.
The code for all standard functions is available in library files, like cs.lib, and
graphics.lib. These library files are supplied by the vendor of compiler. Where
these libraries are stored in the system depends on the compiler. For example, if
you are using Turbo C, you find libraries in LIB directory under directory where
Turbo C is installed.
Declarations about standard functions are available in header files such as stdio.h,
and string.h. Turbo C provides around 400 functions covering various areas like
Screen IO, graphics, disk IO etc.
User-defined functions
User-defined function is a function that is defined by user. That means, the code
for the function is written by user (programmer). User-defined functions are
similar to standard functions in the way you call. The only difference is instead of
C language providing the function, programmer creates the function.
If a program is divided into functional parts than each part may be independently coded
and later combined into single unit.
Advantages of Functions:
 The length of the source program can be reduced by using functions at
appropriate places.
 It becomes easier to locate a faculty functions.
 Many other programs may use a function.

User-defined functions are used mainly for two purposes:


(1) To avoid repetition of code
In programming you often come across the need to execute the same code in
different places in the program. For example, if you have to print an array at the
beginning of the program and at the end of the program. Then you need to write
the code to display the array twice.
If you create a function to display the array, then you have to call the function
once at the beginning of the program. That means, the source code need not be
written for multiple times. It is written only for once and called for multiple times.
(2) To break large program into smaller units
It is never a good idea to have a single large code block. If you write entire C
program as one block, the entire blocks ends up in main() function. It becomes
very difficult to understand and manage.

Prepared by : Prof. Jahnavi Shukla Page 113


If you can break a large code block into multiple smaller blocks, called functions,
then it is much easier to manage the program. In the following example, instead
of taking input, processing and displaying output in main() function, if you can
divide it into three separate functions, it will be much easier to understand and
manage.
main()
{

/* take input here */


...

/* process the input here */


...

/* display output here */


...

}
Single large main() function

main()
{
takeinput();
process();
displayoutput();
}

takeinput()
{
}
process ()
{
}
displayoutput()
{
}

Main() function calling other functions


Creating user-defined function
A user-defined function is identical to main() function in creation. However, there are
two differences between main function and a user-defined function.
 Name of main() function is standard, whereas a user-defined function can have
any name.
 main() function is automatically called when you run the program, whereas a
user-defined function is to be explicitly called.
Terminology of Functions

Function Declaration:
A function may contain declaration and definition. Function declaration specifies
function name, return type, and type of parameters. This is normally given at the
beginning of the program.

Prepared by : Prof. Jahnavi Shukla Page 114


The following is the syntax for function declaration.
return-type functionname ( parameters );
Function declaration is called as Prototype declaration. Though it is not necessary in
majority of cases, it is needed in cases where the following conditions apply:
 Call to function comes before definition of the function
 Function returns non-integer value.
Function Definition:
Function definition is where the statements to be executed are given. When the function
is called the statements given here are executed.
return-type functionname ( parameters )
{
statements;
return value;
}
Return type specifies the type of value function returns. If function doesn’t return any
value then it must be void.
Parameters are formal parameters of the function.
Statements are the statements to be executed when function is called.
Return statement is used to return a value from function.

Caller and Callee


The function which calls another function is called caller function. The function which is
called by the caller is called callee .
Example of User Defined Function

Passing Parameters:
A parameter or argument is a value passed to function so that function can use that value
while performing task. A function may take none, one or more parameters depending
upon the need.
Example: line(); /*function that pass no parameters*/
line(20); /*function that pass one parameter*/
getaverage(10,20); /*function that pass more than one parameter*/
Actual Parameter: It is the value that is passed to function while calling the function. For
example; 10 and 20 values that we passed to line() and getaverage() function in the
above are actual parameters.
Formal Parameter: Variable that is used to receive actual parameter is called formal
parameter.
Example: getaverage(int a, int b); Here a and b are formal parameters.

Returning Value:
Normally after performing the task functions return a value. The return value may be of
Prepared by : Prof. Jahnavi Shukla Page 115
any type. But a function can return only one value. To return a value from the function,
we have to first specify what type of value the function returns and then we have to use
return statement in the code of the function to return the value.

Prepared by : Prof. Jahnavi Shukla Page 116


When return type is not explicitly mentioned it defaults to int. If a function doesn't
return any value then specify return type as void.
A function returns the value to the location from where it has been called.

Category of Functions:
A function depending on whether arguments are present or not and whether a value is
returned or not may belong to one of the following categories:
1. Functions with no arguments and no return value.
2. Functions with arguments and no return value.
3. Functions with arguments and return value.
4. Functions with no arguments and return value.
Functions with no arguments and no return value
When a function has no argument, it does not receive any data from calling function.
When it does not return a value, the calling function does not receive any data from
called function. In effect, there is no data transfer between calling function & called
function.
Program 1:
#include<stdio.h>

Void print(); // function declaration


main()
{
printf("Text in main Function\n");
print(); // function call
}
Void print() // function defination
{
printf("\nText in print function");
}
Program 2:
#include<stdio.h>

Void sum ();


main()

{
printf("Addition of 2 numbers:\n");
sum();
}
void
sum()
{ int a,b;
printf("Enter 2 numbers: ");
scanf("%d %d",&a,&b);
printf("\nSum of %d and %d is %d",a,b,a+b);

}
Prepared by : Prof. Jahnavi Shukla Page 117
Functions with no arguments and return value
When a function has no argument, it does not receive any data from calling function.
When it does return a value, the calling function receives data from called function. In
effect, there is data transfer between called function & calling function.
Program:
#include<stdio.h>
float average();
main()
{
float avg;

printf("Average of 3 numbers:\n");
avg = average();
printf("Average: %f",avg);
}
float average()
{
int a,b,c,s;
printf("Enter 3 numbers: ");
scanf("%d %d %d",&a,&b,&c);
s=a+b+c;
return s/3.0;
}
Functions with arguments and no return value
When a function has argument(s), it does receive data from calling function. When it
does not return a value, the calling function receives does not data from called function.
In effect, there is data transfer between calling function & called function.
Program 1:

#include<stdio.h>
void dline ();

main()
{
dline(15);
printf("\nFunctions...");
dline(15);
getch();
}
void dline(int n)
{
int l;
for(l=0;l<n;l++)
putch('-');
}
Program 2:
#include<stdio.h>
void interest(float,int,float);
main()
Prepared by : Prof. Jahnavi Shukla Page 118
{
int t;
float p,r;
printf("Enter principal amount: ");
scanf("%f",&p);
printf("Enter time period: ");
scanf("%d",&t);
printf("Enter rate: ");
scanf("%d",&r);
interest(p,t,r); // function call….
}
void interest(float pr,int tp,float rate) // function defination
{
float si;

Prepared by : Prof. Jahnavi Shukla Page 119


si = (pr*tp*rate)/100;
printf("Simple Interest for Rs %0.2f is %0.2f",pr,si);
}
Functions with arguments and return value
When a function has an argument, it receives back any data from calling function. When
it returns a value, the calling function receives any data from called function. In effect,
there is a data transfer between the calling function & called function.
Program:
int getsum(int n);
main()
{
int v,sum;
printf("Enter n value: ");
scanf("%d",&v);
sum = getsum(v);
printf("Sum=%d",sum);
}
int getsum(int n)
{
int s=0;
for(;n>0;n--)
s+=n;
return s;
}

Prepared by : Prof. Jahnavi Shukla Page 120


Storage Classes
Properties of a variable:
A variable in C language is associated with the following properties:
Property Meaning
Name is used to refer to variable. This is a symbol using which the
Name
value of the variable is accessed or modified.
Data type Specifies what type of value the variable can store
The value that is stored in the variable. The value is not known
Value
unless the variable is explicitly initialized.
The address of the memory location where the variable is allocated
Address
Space
Specifies the region of the program from where variable can be
Scope
accessed.
Visibility Specifies the area of the program where variable is visible.
Extent Specifies how long variable is allocated space in memory.

Blocks:
C is a block structured language. Blocks are delimited by { and }. Every block can have its
own local variables. Blocks can be defined wherever a C statement could be used. No
semi-colon is required after the closing brace of a block.
Scope
The area of the program from where a variable can be accessed is called as scope of the
variable. The scope of a variable determines over what parts of the program a variable is
actually available for use (active). Scope of the variable depends on where the variable is
declared. The following code illustrate the scope of a variable:
int g; /* scope of g is from this point to end of program */
main()
{
int x; /* scope of x is throughout main function */
. . . .
}
void sum()
{
int y; /* scope of y is throughout function sum */
. . . .
}

The scope of a variable may be either global or local.

Prepared by : Prof. Jahnavi Shukla Page 121


Global Scope: It means the variable is available throughout the program. It is available to
all functions that are defined after the declaration of the variable. This is the scope of the
variables, which are declared outside of all functions. Variables that have global scope are
called as Global Variables.
In the above example, variable g has global scope; that means the variable is accessible to
all the functions of the program (main, sum) that are defined after the variable is defined.
Local Scope: Variables declared at the beginning of the block are available only to that
block in which they are declared. When the scope of the variable is confined to block it is
called as Local Scope. Variables with local scope are called as Local Variables.
In the above example, variables x and y have local scope; that means the variables are
accessible only to the functions at which they are declared.
C allows you to create variables not only at the beginning of a function, you can also
declare variables at the beginning of the block.
main()
{
int x; /* scope of x is throughout main function */
. . . .
if( ...) {
int p; /* scope of p is accessible only within if block */
. . . .
}
else {
int q; /*scope of q is accessible only within else block*/
. . . .
}
}

You cannot change the scope of a variable, it is completely dependent on the place of
declaration in the program.
Visibility:
Normally visibility and scope of variables are same. In other words, a variable is visible
throughout its scope.
Visibility means the region of the program in which a variable is visible. A variable can
never be visible outside the scope. But it may be invisible inside the scope.
int g; /* scope of g is from this point to end of program */
main()
{
int x; /* scope of x is throughout main function */
. . . .
}
Prepared by : Prof. Jahnavi Shukla
void sum()
{
int y; /* scope of y is throughout function sum */
int g;
g=20; /* local variable g is used not global variable g */
}

In the above code, variable g has global scope. But it becomes invisible throughout the
function sum as a variable with the same name is declared in that function.
When a global variable is re-declared in a function then the local variable takes
precedence i.e., g in function sum will reference g in function but not g declared as global
variable. So, in this case though g has scope throughout program, it is not visible
throughout function sum.

For global variable to get its visibility in a function, when a local variable with same
variable name is declared and use we use scope resolution operator(::). This helps in
accessing global variable even though another variable with same name is existing.
int g; /* scope of g is from this point to end of program */
main()
{
int x; /* scope of x is throughout main function */
. . . .
}
void sum()
{
int y; /* scope of y is throughout function sum */
int g;
g=20; /* local variable g is used not global variable g */
::g=g+10; /*global variable g is used now with the operator*/
/*'::' called scope resolution operator*/
}

Extent/Lifetime
Also called as Longevity. This refers to the period of time during which a variable resides
in the memory and retains a given value during the execution of a program. Longevity
has a direct effect on the utility of a given variable.
A variable declared inside a block has local extent. Because it exists in the memory as
long as the block is in execution. It is created when block is invoked and removed when
the execution of the block is completed.
On the other hand, variable declared outside all functions has static extent as they remain
in memory throughout the execution of program.

Prepared by : Prof. Jahnavi Shukla


Though variable is available in memory, we can access it only from the region of the
program to which the variable is visible. That means, just because the variable is there in
the memory we cannot access it.

STORAGE CLASS SPECIFIERS


'Storage' refers to the scope of a variable and memory allocated by compiler to store that
variable. Scope of a variable is the boundary within which a variable can be used.
Storage class defines the scope and lifetime of a variable.
From the point view of C compiler, a variable name identifies physical location from a
computer where variable is stored. There are two memory locations in a computer
system where variables are stored as: Memory and CPU Registers.
Functions of storage class:
 To determine the location of a variable where it is stored?
 Set initial value of a variable or if not specified then setting it to default value.
 Defining scope of a variable.
 To determine the life of a variable.
Syntax:
[storage-class] data type variable [= value] ;
Types of Storage Classes
 auto
 register
 static
 extern

auto or Automatic Storage class


This is normally not used as it is always implicitly associated with all local variables. The
keyword used for this storage class is auto. An auto variable is automatically created and
initialized when control enters into a block and removed when control comes out of
block.
auto int i=30; /*an auto variable with local scope and extent*/
Storage Location: Main Memory
Default Value: Garbage
Scope: Local to the block in which variable is declared
Lifetime: till the control remains within the block.
Example: Program to illustrate how auto variables work.
main() {
auto int i=10;
clrscr();

Prepared by : Prof. Jahnavi Shukla


{
auto int i=20; Output:
20 10
printf("%d",i);
}
printf("\t%d",i);
}

register or Register Storage class


We can tell the compiler that a variable should be kept in registers (which are memory
locations on microprocessors used for internal operations), instead of keeping in the
memory (where normal variables are stored).
Since a register access is much faster than a memory access, keeping the frequently
accessed variables (e.g. loop control variables) in the registers will lead to faster
execution of program. Most of the compilers allow only int or char variables to be
placed in the register.
register int i;

The above is a request to the compiler to allocate a register to variable i instead of


allocating memory. If the register is available then i is placed in register, otherwise it is as
usual given memory location.
The programmer doesn't know whether register is allocated or memory is allocated to a
variable that is used with register storage class. So, it is not possible to use address
operator (&) with variables that contain register storage specifier. This is of the fact that
registers do not contain address.
It is not applicable for arrays, structures or pointers. It cannot not used with static or
external storage class.
Storage Location: CPU registers
Default Value: Garbage
Scope: Local to the block in which variable is declared
Lifetime: till the control remains within the block.

Since, there are limited number of register in processor and if it couldn't store the variable
in register, it will automatically store it in memory.
Example:
main()
{
register int i;
for(i=0;i<10000;i++)
. . . .
}

Prepared by : Prof. Jahnavi Shukla


static or Static Storage Class
static is the default storage class for global variables. This is used to promote local extent
of a local variable to static extent.
The value of static variables persists until the end of the program. A variable can be
declared static using the keyword static like
static int x;
static float y;

When you use static storage class while declaring local variable, instead of creating the
variable and initializing it whenever control enters the block, the variable is created an d
initialized only for once - when variable's declaration is encountered for first time. So a
variable with static extent will remain in the memory across function calls.
Storage Location: Main Memory
Default Value: Zero
Scope: Local to the block in which variable is declared
Lifetime: till the value of the variable persists between different function calls.
Example: Program to illustrate the properties of a static variable.
main() {
int i;
for (i=0; i<3; i++)
incre();
}
incre() {
int avar=1;
static int svar=1;
avar++; svar++;
printf("\n Automatic variable value : %d",avar);
printf("\t Static variable value : %d",svar);
}
Output:
Automatic variable value: 2 Static variable value: 2
Automatic variable value: 2 Static variable value: 3
Automatic variable value: 2 Static variable value: 4

extern or External Storage class:


extern is used to give a reference of a global variable that is visible to ALL the program
files. When you use 'extern' the variable cannot be initialized as all it does is point the
variable name at a storage location that has been previously defined.
External variable can be accessed by any function. They are also known as global
variables. Variables declared outside every function are external variables.

Prepared by : Prof. Jahnavi Shukla


When you have multiple files and you define a global variable or function which will be
used in other files also, then extern will be used in another file to give reference of
defined variable or function.
In case of large program, containing more than one file, if the global variable is declared
in file 1 and that variable is used in file 2 then, compiler will show error. To solve this
problem, keyword extern is used in file 2 to indicate that, the variable specified is global
variable and declared in another file.
/* File1.c */
extern int count; /* refers to an external variable count */
inccount() {
count++;
}

/* File2.c */
#include"File1.c"
int count; /* creates variable count with static extent */
main() {
. . .
}

In this case program File1.c has to access the variable defined in program File2.c.
Storage Location: Main Memory
Default Value: Zero
Scope: Global/File Scope
Lifetime: as long as the program execution doesn't come to an end.
Example: Program to illustrate extern storage class
write.c
void write_extern();
extern int count;
void write_extern()
{
count = count + 2;
printf("Count is %d\n",count);
Output:
}
Count is 7
mmain.c Count is 9
#include"write.c"
int count=5;
main() {
write_extern();
write_extern();
}

Prepared by : Prof. Jahnavi Shukla


Topics
1 Parameter Passing Techniques
2 Passing Parameters Types
3 Recursion
------------------
Parameter Passing Techniques: Call by Value & Call by Reference
Call by Value:
If data is passed by value, the data is copied from the variable used in main() to a
variable used by the function. So if the data passed (that is stored in the function
variable) is modified inside the function, the value is only changed in the variable used
inside the function.
W hen we call a function then we will just pass the variables or the arguments and we
doesn’t pass the address of variables , so that the function will never effects on the values
or on the variables.
So Call by value is that the values those are passed to the functions will never effect the
actual values those are Stored into the variables.
Example: Program to illustrate the concept of call by value
#include <stdio.h>
swap (int, int);
main()
{
int a, b;
printf("\nEnter value of a & b: ");
scanf("%d %d", &a, &b);
printf("\nBefore Swapping:\n");
printf("\na = %d\n\nb = %d\n", a, b);
swap(a, b);
printf("\nAfter Swapping:\n");
printf("\na = %d\n\nb = %d", a, b);
getch();
}
swap (int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
}
Output:
Enter value of a & b: 2 3

Prepared by : Prof. Jahnavi Shukla


Before swapping: 2 3
After swapping: 2 3

Prepared by : Prof. Jahnavi Shukla


Call by Reference:
If data is passed by reference, a pointer to the data is copied instead of the actual
variable as it is done in a call by value. Because a pointer is copied, if the value at that
pointers address is changed in the function, the value is also changed in main().
In the call by reference we pass the address of the variables whose arguments are also
send. So that when we use the reference then, we pass the address the variables.
When we pass the address of variables to the arguments then a function may effect on
the variables. So, when a function will change the values then the values of variables gets
automatically changed and when a function performs some operation on the passed
values, then this will also effect on the actual values.
Example: Program to illustrate the concept of call by reference
#include <stdio.h>
swap (int *, int *);
main()
{
int a, b;
printf("\nEnter value of a & b: ");
scanf("%d %d", &a, &b);
printf("\nBefore Swapping:\n");
printf("\na = %d\n\nb = %d\n", a, b);
swap(&a, &b);
printf("\nAfter Swapping:\n");
printf("\na = %d\n\nb = %d", a, b);
getch();
}
swap (int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
Output:
Enter value of a & b: 2 3
Before swapping: 2 3
After swapping: 3 2

Passing an array as argument to function:


An array is actually held as an address to an area of memory. This means that when you
come to pass it into a function, it can only be passed in as a reference.

Also, when you define the parameter to read in the data in the function prototype, you
declare it as though you were reading in a single-item variable instead of an array. When
an array is passed as parameter, only the name of the array is given at the time of calling
function the formal parameter is to be declared as an array.

Prepared by : Prof. Jahnavi Shukla


It is then up to the function to read the first item from the array, move the pointer along
to the next item, and then carry on until it finds the end of the array - thus, it has to
somehow know how long the array is.
function_name(int x[5])
function_name(int x[])
The parameter x in the above declarations are also internally taken as an integer pointer
by C to access the elements of the array from the first element.
Passing a 1-dimensional array as argument to function:
Example 1: Program to print the given array
printarray(int []);
main()
{
int a[5],i;
for(i=0;i<5;i++)
scanf("%d",&a[i]);
printarray(a);
}
printarray(int ar[5])
{
int i;
for(i=0;i<5;i++)
printf("%d\n",i[ar]);
}

Example 2: Program to find largest from the given array


#define SIZE 50
int big(int [], int);
main()
{
int a[SIZE], n, i, b;
printf("\nEnter size of array: ");
scanf("%d", &n);
printf("\nEnter elements:\n");
for (i=0; i<n; i++)
scanf("%d", &a[i]);
b = big(a, n);
printf("\nLargest number: %d", b);
}
int big(int a[], int n)
{
int b, i;
b = a[0];
for(i=0; i<n; i++)
if (a[i] > b) b = a[i];
return b;
}

Prepared by : Prof. Jahnavi Shukla


Passing a 2-dimensional array as argument to function:
Example: Program to find Diagonal elements of given matrix
#define ROW 10
#define COL 10
int trace(int [][], int, int);
main()
{
int a[ROW][COL], row, col, i, j, sum;
printf("\nEnter no. of rows and columns of a matrix: ");
scanf("%d %d", &row, &col);
printf("\nEnter elements:\n");
for (i=0; i<row; i++)
for (j=0; j<col; j++)
scanf("%d", &a[i][j]);
printf("\nMatrix is:\n\n");
for (i=0; i<row; i++)
{
for (j=0; j<col; j++)
printf("\t%d", a[i][j]);
printf("\n");
}
sum = trace(a, row, col);
printf("\nSum: %d", sum);
}
int trace(int x[ROW][COL], int r, int c)
{
int i, j, s=0;
for (i=0; i<r; i++)
for (j=0; j<c; j++)
if (i == j) s = s + x[i][j];
return s;
}
Passing String as Parameter to function
This is similar to the concept of passing an array to a function as argument. With strings
(i.e. character arrays) - we have one advantage: we know that the end of the array is
marked by a zero character, so as long as we know where the beginning of the array is,
we can find the end of the string of characters by moving from the beginning of the array
to the end one-character at a time.
Example: Program to modify a string and display.
main()
{
char st[20];
printf("Enter Name: ");
gets(st);
modifystring(st);
printf("\n%s",st);
}
modifystring(char st[20]) {
strcat(st," Welcome");

Prepared by : Prof. Jahnavi Shukla


}

Calling Function within Function


One of the main reasons of using various functions in your program is to isolate
assignments; this allows you to divide the jobs among different entities so that if
something is going wrong, you might easily know where the problem is.
Functions trust each other, so much that one function does not have to know HOW the
other function performs its assignment. One function simply needs to know what the
other function does, and what that other function needs.
Once a function has been defined, other functions can use the result of its assignment.
Imagine you define two functions A and B.

If Function A needs to use the result of Function B, function A has to use the name of
function B. This means that Function A has to “call” Function B:

When calling one function from another function, provide neither the return value nor
the body, simply type the name of the function and its list of arguments, if any.
Example: Program to call function inside a function.
main()
{
processinput();
getch();
}
processinput()
{
int a,b,sum;
printf("Enter 2 numbers: ");
scanf("%d %d",&a,&b);
sum = process(a,b);
displayresult(a,b,sum);
}
process(int a,int b)
{
return a+b;
}
displayresult(int x,int y,int s)

Prepared by : Prof. Jahnavi Shukla Page 133


{
printf("Sum of 2 numbers %d and %d is %d",x,y,s);
}

Recursion

Recursion is a process of defining something in terms of itself and is sometimes called


circular definition. When a function calls itself it is called as recursion. Recursion is natural
way of writing certain functions.
Recursive Function: A function is said to be recursive if a statement in the body of the
function calls itself. Each recursive function must specify an exit condition for it to
terminate, otherwise it will go on indefinitely.
A simple example of recursion is presented below:
main()
{
printf("\nThis is an example of recursion");
main();
}

When executed, this program will produce an output like:


This is an example of recursion
This is an example of recursion



This is an example of recursion

Execution must be terminated abruptly (suddenly or unexpected) or forcibly, otherwise


the execution will continue infinitely.
Recursive functions can be effectively used to solve problems where the solution is
expressed in terms of successively applying the same solution of the subset of the
problem.
When we write recursive functions we must have an if statement somewhere to force the
function to return without recursive calls being executed. Otherwise function will never
return back and will be terminated with an error saying “out of stack space”.
Example: Program to find sum of n below numbers using recursion.
#include <stdio.h>
main()
{
int n,sum;
printf("\nEnter n value: ");
scanf("%d", &n);
sum = sum_num(n);
printf("\nSum of %d below numbers is %d",n,sum);
getch();
Prepared by : Prof. Jahnavi Shukla Page 134
}
sum_num(int n)
{
if (n == 1)
return n;
else
return n+sum_num(n-1);
}

Prepared by : Prof. Jahnavi Shukla Page 135


sum_num(5) returns (5 + sum_num(4),

which returns (4 + sum_num(3),

which returns (3 + sum_num(2),

which returns (2 + sum_num(1),

which returns (1)))))


Example: Program to find factorial of given number using recursion.
#include <stdio.h>
long fact(int);
main()
{
int n;
long f;
printf("\nEnter number to find factorial: ");
scanf("%d", &n);
f = fact(n);
printf("\nFactorial: %ld", f);
getch();
}

long fact(int n)
{
int m;
if (n == 1)
return n;
else
return n * fact(n-1);
}

Prepared by : Prof. Jahnavi Shukla Page 136


Example: Program to find the GCD of two given integers using Recursion
#include<stdio.h>
#include<conio.h>
int gcd (int, int); //func. declaration.
void main( )
{
int a, b, res;
clrscr( );
printf("Enter the two integer values:");
scanf("%d%d", &a, &b);
res= gcd(a, b); // calling function.
printf("\nGCD of %d and %d is: %d", a, b, res);
getch( );
}
int gcd( int x, int y) //called function.
{
int z;
z=x%y;
if(z==0)
return y;
gcd(y,z); //recursive function
}
Example: Program to generate the Fibonocci series using Recursion.
#include<stdio.h>
#include<conio.h>
int fibno(int); // function declaration.
void main()
{
int ct, n, disp;
clrscr( );
printf("Enter the no. of terms:");
scanf("%d", &n);
printf("\n The Fibonocci series:\n");
for( ct=0; ct<=n-1; ct++)
{
disp= fibno(ct); //calling function.
printf("%5d", disp);
}
getch( );
}

int fibno( int n)

{
int x, y;
if(n==0)
return 0;
else if(n==1)
return 1;
else
{
Prepared by : Prof. Jahnavi Shukla Page 137
x= fibno( n-1);
y= fibno( n-2);
return (x+y);
}
}

Prepared by : Prof. Jahnavi Shukla Page 138


Prepared by : Prof. Page 139
Jahnavi Shukla

You might also like