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

Unit V Functions

The document discusses functions in C programming. It defines functions as self-contained blocks of code that perform specific tasks. There are two types of functions: library functions which are predefined, and user-defined functions which must be defined by the programmer. Functions help break large programs into smaller, more manageable pieces to make coding, debugging, and testing easier. The document provides examples of several common math library functions like abs(), ceil(), floor(), sin(), cos(), and tan().

Uploaded by

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

Unit V Functions

The document discusses functions in C programming. It defines functions as self-contained blocks of code that perform specific tasks. There are two types of functions: library functions which are predefined, and user-defined functions which must be defined by the programmer. Functions help break large programs into smaller, more manageable pieces to make coding, debugging, and testing easier. The document provides examples of several common math library functions like abs(), ceil(), floor(), sin(), cos(), and tan().

Uploaded by

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

Unit V

Functions
10 Hours
14 Marks
Industry identified competency addressed by this course:
- Develop C programs to solve broad-based computer related problems.

Course Outcome addressed by Unit:


- Develop or use functions in C programs for modular programming approach.

Learning Outcomes those are to be achieved through practical:


- Develop programs to demonstrate use of all string handling functions. (Expt. No.
13)(Compulsory)
- Develop program to demonstrate use of few mathematical functions. (Expt. No. 13)
(Compulsory)
- Develop program to demonstrate use of few other miscellaneous functions. (Expt. No.
13) (Compulsory)
- Develop program to create function to find GCD of given number. Call this function
in program. (Expt. No. 14)
- Develop program to find factorial of a given number using recursion. (Expt. No. 14)

Major Learning Outcomes (Cognitive Domain):


5a. Use given library functions.
5b. Develop relevant user-defined functions for given problem.
5c. Write „C‟ code to pass given function parameters using “call by value” and “call by
reference” approach.
5d. Write recursive function for the given problem.

Affective Domain Outcomes:


- Follow safety practices.
- Practice energy conservation.
- Follow ethical practices.

Topics and Subtopics:


5.1.Concept and need of function.
5.2.Library functions – Math functions, string handling functions, other miscellaneous
functions.
5.3.Writing user defined functions, Scope of variables.
5.4.Parameter passing – Call by value, Call by reference.
5.5.Recursive functions.

Suggested specification table:


Distribution of Theory Marks
Remember Level Understand Level Apply and Above Level Total Marks
02 04 08 14
This specification table provides general guidelines to assist students for their learning
and to teachers to teach and assess students with respect to attainment of Learning
Outcomes (LOs). The actual distribution of marks at different taxonomy levels (R, U and
A) in the question paper may vary from above table.
1 of 20
5.1 Functions

Functions are building blocks of a C program. We have already defined


main( ) function in every C program. Functions are used for breaking large
computer tasks into smaller pieces. Due to use of functions code gets divided into
independent blocks of code. This helps to achieve concept of modular
programming. i.e. Different programmers may work on different modules
(functions) and then can combine all these modules to get final product.
Functions once written by a programmer can be reused by him/her or
other programmers afterwards. It results in saving of time required for coding.

5.1.1 Real-life analogy of Function


In day-to-day life we do not perform all the tasks by ourselves. Some tasks
are always taken done by some other persons or specialists. If our cell phone is
not working properly, we get it serviced/repaired by a specialist. There are so
many other tasks for which we require help of others.
Getting a specific task done by a specific person resembles to getting a
small task done by a function.

5.1.2Definition of Function
Function is a self-contained block of statements that performs a specific
task.

5.1.3 Types of functions


Functions can be broadly classified as
- Library Functions
- User-defined functions

Library functions are already defined functions and they can be directly
used by a programmer by just including the header file in which they are
defined. We have already used printf( ) and scanf( ) library functions for using
which we have included the header file stdio.h.
User-defined functions need to be defined by a programmer as per his/her
requirements. These functions can be used by the same programmer or other
programmers afterwards.

5.1.4 Need of functions


By using functions, bigger task gets divided into smaller tasks. Due to this
complexity of the problem gets reduced.
Understanding smaller functions is easier as compared to bigger program.
Function hides unnecessary details from other parts of program. (e.g. As
user of a cell phone only needs to know its functionality, no need to know its
hardware details.)
If a program becomes larger, debugging and testing becomes difficult. To
overcome this problem, program is divided into smaller functions those can be
easily coded, debugged and tested.
Once a function is defined it can be easily reused.
Functions help in achieving modular programming.

2 of 20
5.1.5 Prototype of Function
Argument is nothing but a value or reference passed to a function. We
can pass any number of arguments (0 or more) to a function. They are also called
as parameters.
Also, function may return a value (maximum one value can be returned by
a function). Return-type of a function is data type of value which function is
returning. If a function does not return any value, its return-type is considered to
be „void‟.
Every function is uniquely identified by its prototype. Prototype of a
function is nothing but combination of return-type, name of function (i.e.
identifier used for function), number of arguments and types of arguments.
Prototype of a function is used for uniquely identifying a function. Syntax of a
prototype is given below.

return-type function-name(datatype-of-arg1,datatype-of-arg2,…)

Examples:
1.
int add(int,int)
Function named „add‟ takes two arguments both of type
integer and returns an integer value.
2.
void display_division(float,float)
Function named „display_division‟ takes two arguments both
of type float and does not return any value.
3.
void disp( )
Function named „disp‟ does not take any arguments and does
not return any value.
4.
int get_val( )
Function named „get_val‟ does not take any arguments and
returns an integer value.

5.2 Library Functions

As discussed before, library functions can be directly used by a


programmer by just including the header file in which they are defined. There is
no need to define these functions by a programmer.They are also referred as
inbuilt functions as they are already defined.
C has a very strong library of functions. Some of them are discussed below.

5.2.1 Math functions


C has a header file named math.h in which various functions related to
mathematical operations are defined. Some of them are discussed below.

abs( ) function:
This function returns absolute value of passed parameter. Prototype of
this function is given below.

3 of 20
int abs(int)
This function expects an integer parameter and returns an integer value.

Example:
int a= – 5634;
int b=831;
printf(“\nAbsolute value of %d is %d”,a,abs(a));
printf(“\nAbsolute value of %d is %d”,b,abs(b));

Output:

Absolute value of – 5634 is 5634


Absolute value of 831 is 831

ceil( ) function:
This function returns nearest higher integer (i.e. ceiling value) of passed
floating-point parameter. Prototype of this function is given below.
double ceil(double)
This function expects a floating-point parameter and returns an integer
value (integer found as double).

Example:
doublex = 6.346;
doubley = 5.754;
printf(“\nCeiling value of %lf is %d”,a,ceil(a));
printf(“\nCeiling value of %lf is %d”,b,ceil(b));

Output:

Ceiling value of 6.346 is 7


Ceiling value of 5.754 is 6

floor( ) function:
This function returns nearest lower integer (i.e. floor value) of passed
floating-point parameter. Prototype of this function is given below.
double floor(double)
This function expects a floating-point parameter and returns an integer
value (integer found as double).

Example:
double x = 6.346;
double y = 5.754;
printf(“\nFloor value of %lf is %d”,a,floor(a));
printf(“\nFloor value of %lf is %d”,b,floor(b));

Output:

Floor value of 6.346 is 6


Floor value of 5.754 is 5

4 of 20
sin( ), cos( ), tan( ) functions:
These functions return sine, cosine and tangent of passed floating-point
parameter (in radians). Prototypes of these functionsare given below.
double sin(double)
double cos(double)
double tan(double)

These functions expect a floating-point parameter (as angle in radians)


and return floating-point value of sine, cosine and tangent respectively.

Example:
/*M_PI is a predefined constant defined in math.h for value of pi. */
printf(“\nsin(30)= %lf”,sin(M_PI/6)); /*πC=1800 */
printf(“\ncos(60) = %lf”,cos(M_PI/3));
printf(“\ntan(45) = %lf”,tan(M_PI/4));

Output:

sin(30) = 0.5
cos(60) = 0.5
tan(45) = 1.0

pow( ) function:
This function returns first parameter raised to the power second
parameter. Prototype of this function is given below.
double pow(double,double)
This function expects two floating-point parameters and returns an
floating-point value.

Example:
double x = 3;
double y = 4;
printf(“\n%lf raised to power %lf = %lf”,x,y,pow(x,y));

Output:

3.0 raised to power 4.0 = 81.0

sqrt( ) function:
This function returns square root of its argument. Prototype of this
function is given below.
double sqrt(double)
This function expects floating-point parameter and returns an floating-
point value.

Example:
double x = 256;
printf(“\nSquare root of %lf is %lf”,x.sqrt(x));

5 of 20
Output:

Square root of 256.0 is 16.0

5.2.2 String handling functions


C has a header file named string.h in which various functions related to
handling of strings are defined. Some of them are discussed below.

strlen( ) function:
This function returns length of string(i.e. number of characters in the
string) passed as parameter. Prototype of this function is given below.
int strlen(char *)
This function expects a string parameter and returns an integer value.

Example:
char name[ ]=“SainaNehwal”;
printf(“Length of the string is %d”,strlen(name));

Output:
Length of the string is 12

strcpy( ) function:
As string is not a basic data type in C, we cannot directly assign a string to
another character array using „=‟ operator. The function strcpy( ) is used for
string-assignment. Prototype of this function is given below.
void strcpy(char *destination, char *source)
This function takes two parameters. Contents of source string (second
parameter) get assigned to destination string (first parameter).

Example:
char name[ ]=“ViratKohli”;
charcaptain[20];
strcpy(captain,name);
printf(“Original string is %s”,name);
printf(“\nCopied string is %s”,captain);

Output:
Original string is ViratKohli
Copied string is ViratKohli

strcat( ) function:
This function is used for concatenation or joining of two strings. (As string
is not a basic data type in C, we cannot use directly „+‟ operator for
concatenation).Prototype of this function is given below.
void strcat(char *destination, char *source)
Here, destination and source are character arrays. When this function is
executed, source string (second parameter) is appended to destination string
(first parameter) while source string remains as it is.

6 of 20
Example:
charstr1[20]=“Table”;
charstr2[10]=“Tennis”;
strcat(str1,str2);
printf(“str1 is %s”,str1);
printf(“\nstr2 is %s”,str2);

Output:
str1 is TableTennis
str2 is Tennis

strcmp( ) function:
As string is not a basic data type in C, we cannot directly compare two
strings using relational operators. The function strcmp( ) is used for comparing
two strings. It does alphanumeric comparison based on ASCII values of the
characters. (Every character has unique ASCII code i.e. American Standard Code
for Information Interchange). Prototype of this function is given below.
int strcmp(char *string1, char *string2)
This function accepts two parameters as strings and returns an integer
value. Meaning of value returned by this function is discussed in table below.
Return Value Meaning
0 If both the parameter strings are equal (i.e. string1=string2)
<0 If first string is lesser than second string (i.e. string1<string2)
>0 If first string is greater than second string (i.e. string1>string2)

Example:
char str1[ ]=“Vinit”;
char str2[ ]=“Vineet”;
int result;
result=strcmp(str1,str2);
if(result==0)
printf(“Strings are equal”);
if(result<0)
printf(“First string is alphabetically lesser than second string”);
if(result>0)
printf(“First string is alphabetically greater than second string”);

Output:
First string is alphabetically greater than second string

5.2.3 Other miscellaneous functions


In addition to the functions discussed before there are hundreds of useful
library functions in C. Some miscellaneous functions are discussed below. The
functions isalnum( ), isalpha( ), isdigit( ), islower() and isupper( ) are defined in
hader file ctype.h. The functions atoi( ) and atof( ) are defined in header file
stdlib.h.

isalnum( ) function:

7 of 20
This function returns non-zero value if the character passed as parameter
is alphabet („a‟ to „z‟ or „A‟ to „Z‟) or digit („0‟ to „9‟). Prototype of this function is
given below.
int isalnum(char)
This function expects a character parameter and returns an integer value.

isalpha( ) function:
This function returns non-zero value if the character passed as parameter
is an alphabet („a‟ to „z‟ or „A‟ to „Z‟). Prototype of this function is given below.
int isalpha(char)
This function expects a character parameter and returns an integer value.

isdigit( ) function:
This function returns non-zero value if the character passed as parameter
is a digit („0‟ to „9‟). Prototype of this function is given below.
int isdigit(char)
This function expects a character parameter and returns an integer value.

islower( ) function:
This function returns non-zero value if the character passed as parameter
is lowercase alphabet („a‟ to „z‟). Prototype of this function is given below.
int islower(char)
This function expects a character parameter and returns an integer value.

isupper( ) function:
This function returns non-zero value if the character passed as parameter
is uppercase alphabet („A‟ to „Z‟). Prototype of this function is given below.
int isupper(char)
This function expects a character parameter and returns an integer value.

atoi( ) function:
This function returns integer value of the string passed as parameter.
Prototype of this function is given below.
int atoi(char)
This function expects a character parameter and returns an integer value.

Example:
char str[ ] = “27”;
printf(“Integer value of the string %s is %d”, str, atoi(str));

Output:
Integer value of the string 27 is 27

atof( ) function:
This function returns floating-point value of the string passed as
parameter. Prototype of this function is given below.
double atoi(char)
This function expects a character parameter and returns a double value.

8 of 20
Example:
char str[ ] = “589.432”;
printf(“Floating-point value of the string %s is %d”, str, atof(str));

Output:
Integer value of the string 589.432 is 589.432

5.3 User-defined functions and scope of variables

5.3.1 Writing User-defined functions


As discussed before, user-defined functions need to be defined by a
programmer as per his/her requirements. These functions can be used by the
same programmer or other programmers afterwards.
We have already discussed about arguments and return-value of a
function. Let us discuss about some other important aspects of functions that are
important while using functions. They are,
- Function Declaration
- Function Definition
- Function Call

Before calling (or defining) a function its prototype must be declared. This
is called function declaration.
Function definition is part of the program where a block of statements
that must be carried out in a function are defined. Function body is nothing
but the block of statements in a function definition.
When a function defined by programmer is to be executed, it should be
called. Function call is a statement used for executing a function. This contains
name of function along with its actual arguments.

Example:
main( )
{
int area_of_rectangle(int,int); /* Function declaration */
int length,breadth,area;

printf(“Enter length and breadth of a rectangle: ”);


scanf(“%d%d”,&length,&breadth);

area = area_of_rectangle(length, breadth); /* Function Call */

printf(“Area of rectangle is %d\n”,area);


}

int area_of_rectangle(int l, int b) /* Function Definition */


{
int a; /* Function body */
a = l * b; /* Function body */
return a; /* Function body */
}
9 of 20
In the above example, as the function named area_of_rectangle( ) is not
known before its call, we have to declare it at the beginning of main( ) function.
This kind of declaration of function before its definition is called forward
declaration.
But, if the function area_of_rectangle( ) is defined before main( ) function,
declaration is no longer required (as function is known in advance). Same is
shown in following example.

Example:

/* Combined Function Definition & Declaration */


int area_of_rectangle(int l, int b)
{
int a; /* Function body */
a = l * b; /* Function body */
return a; /* Function body */
}

main( )
{
int length,breadth,area;

printf(“Enter length and breadth of a rectangle: ”);


scanf(“%d%d”,&length,&breadth);

area = area_of_rectangle(length, breadth); /* Function Call */

printf(“Area of rectangle is %d\n”,area);


}

5.3.2 Categories of Function


Functions can be categorized depending on number of arguments and
whether they are returning a value or not. On this basis, four categories of
functions are,
- Function without argument, without return value
- Function with argument, without return value
- Function without argument, with return value
- Function with argument, with return value

5.3.2.1 Function without argument, without return value


In this category of functions, function does not pass any argument.
Also, it does not return any value. Prototype of this category of function
is as follows,

void function-name( )

Example:
void display( )
{

10 of 20
printf(“Welcome to Modular Programming\n”);
return;
}

5.3.2.2 Function with argument, without return value


In this category of functions, function may pass one or more
arguments. But, it does not return any value. Prototype of this category
of function is as follows,

void function-name(datatype1 [, …])

Example:
void product(int a, int b)
{
int result;
result = a * b ;
printf(“Product of %d and %d is %d\n”,a,b,result);
return;
}

5.3.2.3 Function without argument, with return value


In this category of functions, functions does not pass any
argument. But, it returns a value. Prototype of this category of function
is as follows,

return-type function-name( )

Example:
int getValidAge( )
{
int age;
do
{
printf(“Enter valid age (above 16): ”);
scanf(“%d”,&age);
}while(age<16);
return age; /* Or return(age); */
}

5.3.2.4 Function with argument, with return value


In this category of functions, function may return one or more
arguments. Also, it returns a value. Prototype of this category of function
is as follows,

return-type function-name(datatype1 [, …])

Example:
float area_of_circle(int radius)
{

11 of 20
float a;
a = 3.14 * radius * radius;
return a; /* Or return(a); */
}

5.3.3 Scope and lifetime of variables


Scope of a variable is a part of program within which the variable can
be used. In 'C' scope of a variable is either global or local.
The automatic variables which are declared at the beginning of a function
are local variables for that function. i.e. Scope of such variables is within the
function.
The variables which are declared outside of functions, in global declaration
section are the global variables. Such variables have global scope. i.e. they can
be used by any function within the whole program. In other words, they are
available everywhere in the program.
Lifetime of a variable is the duration in which a variable exists in the
memory during execution. Generally, variable declared in a function (local
variable) exists in memory up to complete execution of function in which it is
declared. Global variables exist in memory up to execution of the complete
program.

5.3.4 Storage Classes


We have studied that every variable has a data type. Along with a data
type, every variable also has a storage class. Storage class of a variable speaks
about where it would be stored, its default initial value and its scope & lifetime.
In C, there are four storage classes. They are:
1. Automatic Storage Class
2. Register Storage Class
3. Static Storage Class
4. External Storage Class

5.3.4.1 Automatic Storage Class


 Variable of this storage class are stored in memory (i.e. main
memory).
 Their default initial value is a random or a garbage value.
 These variables are local to the block where they are declared.
 They retain their values only within the block where they are
declared.
 We may use keyword „auto‟ for declaring automatic variables.
But, if a variable is declared inside a block, it has default storage
class as automatic.
e.g.
void fun1( )
{
int a;
auto int b;
}

Here both the variables a and b have automatic storage class

12 of 20
5.3.4.2 Register Storage Class
 Variable of this storage class are stored in CPU registers due to
which fastest access of such variables is possible.
 Their default initial value is a random or a garbage value.
 These variables are local to the block where they are declared.
 They retain their values only within the block where they are
declared.
 We have to use keyword „register‟ for declaring register variables.
e.g.
void fun2( )
{
register int c;
}

Here variable c has register storage class. If a CPU register is not


free or size of CPU register does not match with the data type of
variable, such variables are treated as automatic variables.

5.3.4.3 Static Storage Class


 Variable of this storage class are stored in memory (i.e. main
memory).
 Their default initial value is zero.
 These variables are local to the block where they are declared.
 They retain their values between different function calls.
 We have to use keyword „static‟ for declaring static variables.
e.g.
void fun3( )
{
static int a;
printf(“%d\n”,a);
a++;
}

main( )
{
fun3( );
fun3( );
fun3( );
fun3( );
}

Output:
0
1
2
3

13 of 20
Here variable „a‟ has static storage class. Therefore it retains its
value in different function calls. As the default value of such
variable is zero, the output above is starting from zero.

5.3.4.4 External Storage Class


 Variable of this storage class are stored in memory (i.e. main
memory).
 Their default initial value is zero.
 These variables are global.
 They retain their values till the execution of whole program.
 We have to use keyword „extern‟ for declaring external variables
which are visible to all the functions and all the files in the
program. But this is just a reference creation. We have to define
the variable again.
 External variable can be either global variable or a variable
declared in another source file.
e.g.
int a;
main( )
{
extern int a;
}

Here variable „a‟ is treated as external variable.

5.4 Parameter Passing

Parameters can be passed to functions in two ways


- Call by value
- Call by reference

5.2.1 Call be value


As already discussed, we can pass arguments while calling function. When
we call a function by passing arguments in the way discussed before, it is called
as call by value. Because, values of the passed arguments are sent to the called
function and called function get them copied to its local variables. This concept is
elaborated with example 1 below.

Example 1:
/* program for product of two numbers */
main( )
{
int result,no1,no2; /* variables result, no1 and no2 are local to main( ) */
int product(int,int);
printf(“Please enter two numbers: ”);
scanf(“%d%d”,&no1,&no2);
result=product(no1,no2); /* here values of no1 and no2 are passed */
printf(“Product of %d and %d is %d\n”,no1,no2,result);
}
14 of 20
/* value of no1 gets copied to x and value of no2 gets copied to y */
int product(int x, int y) /* variables x and y are local to product( ) function */
{
int z; /* variable z is local to product( ) function */
z = x * y;
return(z);
}

As shown in example 2 below, even if arguments are named with same


names in both the functions, these variables are different variables.

Example 2:
/* program for product of two numbers */
main( )
{
int result,no1,no2; /* variables result, no1 and no2 are local to main( ) */
int product(int,int);
printf(“Please enter two numbers: ”);
scanf(“%d%d”,&no1,&no2);
result=product(no1,no2); /* here values of no1 and no2 are passed */
printf(“Product of %d and %d is %d\n”,no1,no2,result);
}

/* value of no1 gets copied to no1 of function product( ) and value of no2 gets
copied to no2 of function product( ). Here even if the names of variables are same,
no1 and no2 variables of main( ) function and no1 and no2 variables of product( )
function are different */
int product(int no1, int no2) /* no1 and no2 are local to product( ) function */
{
int z; /* variable z is local to product( ) function */
z = no1 * no2;
return(z);
}

5.2.2 Call be reference


As seen before, functions get parameters by value. But it may create
problems in some cases. Let us take an example of swapping of variables.

Example 1:
/* program for swapping of two variables (call by value) */
main( )
{
int x,y;
void swap(int,int);
printf(“Please enter two numbers: ”);
scanf(“%d%d”,&x,&y);
printf(“Before swapping: x = %d, y = %d\n”,x,y);
swap(x,y); /* here values of x and y are passed */

15 of 20
printf(“After swapping: x = %d, y = %d\n”,x,y);
}

/* value of x of main( ) gets copied to x and value of y of main( ) gets copied to y */


void swap(int x, int y) /* variables x and y are local to product( ) function */
{
int temp;
temp = x;
x = y;
y = temp;
}

Output:
Please enter two numbers: 24 76
Before swapping: x = 24, y = 76
After swapping: x = 24, y = 76

As seen in the above output, even after execution of swapping function,


original values of x and y are displayed instead of swapped values. This has
happened as x & y variables of main( ) function and x & y variables of swap( )
function are different. As we have passed arguments by value, the change in
value does not get reflected in the variables of main( ) function.
Solution to this problem is „call by reference‟. We can pass the parameters
as reference instead of value. When we pass parameter as reference, address of
the parameter is passed while calling the function and the variable accepting the
parameter points to the memory location of parameter itself.
There are two ways how concept of call by reference can be used. They are
discussed below:
Syntax 1:
/* Function Definition */
return-type function-name(datatype *p1[, datatype *p2, …])
{
}

main( )
{
---
function-name(&p1[,&p2,…]); /* Function Call */
---
}

Syntax 2:
/* Function Definition */
return-type function-name(datatype &p1[, datatype &p2, …])
{
}

main( )
{

16 of 20
---
function-name(p1[,p2,…]); /* Function Call */
---
}

Following examples show how call by reference may be used for swapping
of two variables.

Example 2:
/* program for swapping of two variables (call by reference with syntax 1) */
main( )
{
int x,y;
void swap(int*,int*);
printf(“Please enter two numbers: ”);
scanf(“%d%d”,&x,&y);
printf(“Before swapping: x = %d, y = %d\n”,x,y);
swap(&x,&y); /* here references of x and y are passed */
printf(“After swapping: x = %d, y = %d\n”,x,y);
}

/* Due to call by reference, x & a are same and y & b are same */
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}

Output:
Please enter two numbers: 85 64
Before swapping: x = 85, y = 64
After swapping: x = 64, y = 85

Example 3:
/* program for swapping of two variables (call by reference with syntax 2) */
main( )
{
int x,y;
void swap(int,int);
printf(“Please enter two numbers: ”);
scanf(“%d%d”,&x,&y);
printf(“Before swapping: x = %d, y = %d\n”,x,y);
swap(x,y);
printf(“After swapping: x = %d, y = %d\n”,x,y);
}

/* Due to call by reference, x & a are same and y & b are same */

17 of 20
void swap(int &a, int &b)
{
int temp;
temp = a;
a = b;
b = temp;
}

Output:
Please enter two numbers: 39 71
Before swapping: x = 39, y = 71
After swapping: x = 71, y = 39

5.5 Recursive Functions

Recursion is a process of calling a function by itself. Recursion can be


either direct (Function calling itself directly) or indirect (function calling itself
through another function). The function which is calling itself is said to be a
recursive function. Recursive functions are best-suited for the problems which
are solved by successively applying same solution to each sub-problem. The best
example is calculating factorial of a number.
As we know factorial is calculated as

Recursive definition of factorial is

We may write a recursive function for factorial as,

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

The above function gets called recursively. If we take an example of n=5,


the function gets called recursively as

In function Recursive call Result


fact(5) 5 * fact(4) = 5 * 24 = 120
fact(4) 4 * fact(3) = 4 * 6 = 24
fact(3) 3 * fact(2) =3*2=6
18 of 20
fact(2) 2 * fact(1) =2*1=2
fact(1) 1 * fact(0) =1*1=1
fact(0) 1 =1

Recursive call stops when n become 0. For this example, n=0 is exit
condition of recursion. Complete program for using above function is shown
below.

Example 1:
/* Consider long int as return type because 8!=40320 which is out of range
of int. Same is the case for all the numbers above 8. */
long int fact(int n)
{
if(n==0)
{
return 1;
}
else
{
return (n*fact(n-1));
}
}

main( )
{
int x;
printf(“Enter a number whose factorial is to be found: ”);
scanf(“%d”,&x);
printf(“%d! = %ld ”,x,fact(x));
}

Output:
Enter a number whose factorial is to be found: 6
6! = 720

Sample Questions

1. State any four math functions with its use. [2M]


2. Write syntax and use of pow( ) function of <math.h> header file. [2M]
3. Explain any two string functions with example. [4M]
4. Explain strlen( ) and strcpy( ) functions with example. [4M]
5. State the syntax and use of strlen( ) and strcat( ) function. [2M]
6. Explain user defined function with example. [4M]
7. What is function prototype? Give its example. [2M]
8. What is function prototype? Explain with example. [4M]
9. List categories of functions. List prototype of each. [4M]
10. List categories of functions. Explain any one with suitable example. [4M]
11. Explain no-argument, no-return value function type with example. [4M]
19 of 20
12. With suitable example and syntax explain function declaration. [4M]
13. Write syntax of declaration of function with suitable example. [4M]
14. Define [4M]
i) Function Definition
ii) Function Body
iii) Function Call
iv) Function Prototype
15. Write a program using function to find product of two numbers. [4M]
16. Write a function to calculate area of circle. [4M]
17. Develop a program to find diameter, circumference and area of circle using
functions. [6M]
18. Write a program to perform addition, subtraction, multiplication and
division of two integer numbers using functions. [6M]
19. Write a program to reverse the number using function (1234 to 4321).
[4M]
20. Write a program to read two strings and find whether they are equal or
not. [4M]
21. State the scope of local and global variable. [2M]
22. With suitable example explain what is meant by scope of a variable. [2M]
23. Explain any two storage classes. [2M]
24. Explain in brief auto and extern storage class. [4M]
25. Explain in brief register and static storage class. [4M]
26. Distinguish between call by value and call by reference (2 points). [2M]
27. Distinguish between call by value and call by reference. [4M]
28. Write a function to exchange values of variables. [4M]
29. Write program to swap two numbers using call by value. [4M]
30. Define recursive function. [2M]
31. With suitable example explain what is meant by recursive function. [2M]
32. Explain recursive function with example. [4M]
33. What is recursive function? Explain with example. [4M]
34. Write a recursive program to print Fibonacci series. [4M]
35. Explain recursion with suitable example. List any two advantages. [6M]
36. Develop a program to find factorial of a number using recursion. [4M]
37. Value of a number (N) is entered through keyboard. Write a program
using recursion to calculate and display factorial of number (N). [6M]
38. Write a function to print Fibonacci series starting from 0, 1. [6M]
39. Calculate factorial of a number using recursion. [6M]
40. Write a function to display Fibonacci series up to given number using
recursion. Use function named “Fibbo”. [4M]

20 of 20

You might also like