सी, पायथन, जावास्क्रिप्ट, गो, रस्ट, सॉलिडिटी जैसी भाषाओं और कंप्यूटर साइंस के बुनियादी और गणित के उन्नत सिद्धांतों को हिंदी में पढ़ने के लिए संपर्क करें। हम वेबसाइट और सॉफ्टवेयर भी बनाते हैं।
From the above example, let us analyse the basic steps of a recursive program.
Step 1: Specify the base case which will stop the function from making a call to itself.
Step 2: Check to see whether the current value being processed matches with the value of the base case. If yes, process and return the value.
Step 3: Divide the problem into smaller or simpler sub-problems.
Step 4: Call the function from the sub-problems.
Step 5: Combine the results of the sub-problems.
Step 6: Return the result of the entire problem.
Note
The base case of a recursive function acts as the terminating condition. So, in the absence of an explicitly-defined base case, a recursive function would call itself indefinitely.
4.10.1 Greatest Common Divisor
The greatest common divisor (GCD) of two numbers (integers) is the largest integer that divides both the numbers. We can find the GCD of two numbers recursively by using the Euclid's algorithm that states
GCD(a, b) = b, if b divides a
GCD(b, a mod b), otherwise
GCD can be implemented as a recursive function because if b does not divide a, then we call the same function (GCD) with another set of parameters that are smaller and simpler than the original ones. Here we assume that a > b. However if a < b, then interchange a and b in the formula given above.
Write a program to calculate GCD using recursive functions.
#include <stdio.h>
int GCD(int, int);
int main()
{
int num1, num2, res;
printf("\n Enter the two numbers: ");
scanf("%d %d", &num1, &num2);
res = GCD(num1, num2);
printf("\n GCD of %d and %d = %d", num1, num2, res);
return 0;
}
int GCD(int x, int y)
{
int rem;
rem = x%y;
if(rem==0)
return y;
else
return (GCD(y, rem));
}
Output
Enter the two numbers: 62 8
GCD of 62 and 8 = 2
4.10.2 Finding Exponents
We can find the exponent of a number using recursion. To find x^y, the base case would be when y=0, as we know that any number raised to the power 0 is 1. Therefore, the general formula to find x^y can be given as
EXP(x, y) = 1, if y == 0
x * EXP(x, y-1), otherwise
Write a program to calculate exp(x, y) using recursive functions.
#include <stdio.h>
int exp_rec(int, int);
int main()
{
int num1, num2, res;
printf("\n Enter the two numbers: ");
scanf("%d %d", &num1, &num2);
res = exp_rec(num1, num2);
printf("\n RESULT = %d", res);
return 0;
}
int exp_rec(int x, int y)
{
if( y==0)
return 1;
else
return ( x * exp_rec( x, y-1));
}
Output
Enter the two numbers: 5 3
RESULT = 125
4.10.3 Fibonacci Series
The Fibonacci series can be given as:
0 1 1 2 3 5 8 13 21 34 55 ....
That is, the third term of the series is the sum of the first and second terms. Similarly, fourth term is the sum of second and third terms, and so on. Now we will design a recursive solution to find the n<sup>th</sup> term of the Fibonacci series. The general formula to do so can be given as:
FIB(n) = 0, if n = 0
1, if n = 1
FIB(n - 1) + FIB(n - 2), otherwise
As per the formula, FIB(0) = 0 and FIB(1) = 1 and, FIB(2) = FIB(1) + FIB(0) = 1 + 0 = 1. So we have two base cases. This is necessary because every problem is divided into two smaller problems.
Write a program to print the Fibonacci series using recursion.
#include <stdio.h>
int Fibonacci(int);
int main()
{
int n, i = 0, res;
printf("Enter the number of terms\n");
scanf("%d",&n);
printf("Fibonacci series\n");
for(i = 0; i < n; i++ )
{
res = Fibonacci(i);
printf("%d\t",res);
}
return 0;
}
int Fibonacci(int n)
{
if ( n == 0 )
return 0;
else if ( n == 1 )
return 1;
else
return ( Fibonacci(n-1) + Fibonacci(n-2) );
}
Output
Enter the number of terms 5
Fibonacci series
0 1 1 2 3
4.11 TYPES OF RECURSION
Recursion is a technique that breaks a problem into one or more sub-problems that are similar to the original problem. Any recursive function can be characterized based on:
whether the function calls itself directly or indirectly (direct or indirect recursion),
whether any operation is pending at each recursive call (tail-recursive or not), and
the structure of the calling pattern (linear or tree-recursive).
In this section, we will discuss all these types of recursions.
4.11.1 Direct Recursion
A function is said to be directly recursive if it explicitly calls itself. For example, consider Figure 4.7.
int Func(int n)
{
if(n==0)
return n;
else
return(Func(n-1));
}
Figure 4.7 Direct recursion
Here, Func() calls itself for all positive values of n, so it is said to be a directly recursive function.
4.11.2 Indirect Recursion
A function is said to be indirectly recursive if it contains a call to another function which ultimately calls it. Look at the functions given in Figure 4.8. These two functions are indirectly recursive as they both call each other.
int Func1(int n)
{
if(n==0)
return n;
else
return Func2(n);
}
int Func2(int x)
{
return Func1(x-1);
}
Figure 4.8 Indirect recursion
4.11.3 Tail Recursion
A recursive function is said to be tail recursive if no operations are pending to be performed when the recursive function returns to its caller. When the called function returns, the returned value is immediately returned from the calling function. Tail recursive functions are highly desirable because they are much more efficient to use as the amount of information that has to be stored on the system stack is independent of the number of recursive calls.
For example, the factorial function that we have written is a non-tail-recursive function (Figure 4.9), because there is a pending operation of multiplication to be performed on return from each recursive call.
Whenever there is a pending operation to be performed, the function becomes non-tail recursive. In such a non-tail recursive function (Figure 4.10), information about each pending operation must be stored, so the amount of information directly depends on the number of calls.
However, the same factorial function can be written in a tail-recursive manner as shown in Figure 4.10.
In the code, Fact1 function preserves the syntax of the Fact(n). Here the recursion occurs in the Fact1 function and not in Fact function. Carefully observe that Fact1 has no pending operation to be performed on return from recursive calls. The value computed by the recursive call is simply returned without any modification. So in this case, the amount of information to be stored on the system stack is constant (just the values of n and res need to be stored) and is independent of the number of recursive calls.
int Fact(n)
{
return Fact1(n, 1);
}
int Fact1(int n, int res)
{
if (n==1)
return res;
else
return Fact1(n-1, n*res);
}
Figure 4.10 Tail-recursive function
Converting Recursive Functions to Tail Recursive
A non-tail recursive function can be converted into a tail-recursive function by using an auxiliary parameter as we did in case of the Factorial function. The auxiliary parameter is used to form the result. When we use such a parameter, the pending operation is incorporated into the auxiliary parameter so that the recursive call no longer has a pending operation. We generally use an auxiliary function while using the auxiliary parameter. This is done to keep the syntax clean and to hide the fact that auxiliary parameters are needed.
4.11.4 Linear and Tree Recursion
Recursive functions can also be characterized depending on the way in which recursion grows, i.e., in a linear fashion or forming a tree structure (Figure 4.11).
In simple words, a recursive function is said to be linearly recursive when the pending operation (if any) does not make another recursive call to the function. For example, observe the last line of recursive factorial function. The factorial function is linearly recursive as the pending operation involves only multiplication to be performed and does not involve another recursive call to Fact.
On the contrary, a recursive function is said to be tree recursive (or non-linearly recursive) if the pending operation makes another recursive call to the function. For example, the Fibonacci function Fib in which the pending operations recursively calls the Fib function.
The tower of Hanoi is one of the main applications of recursion. It says, 'if you can solve n-1 cases, then you can easily solve the n<sup>th</sup> case'.
Look at Figure 4.12 which shows three rings mounted on pole A. The problem is to move all these rings from pole A to pole C while maintaining the same order. The main issue is that the smaller disk must always come above the larger disk.
| | |
==|== | |
====|==== | |
======|====== | |
---------------------------------------------
A B C
Figure 4.12 Tower of Hanoi
We will be doing this using a spare pole. In our case, A is the source pole, C is the destination pole, and B is the spare pole. To transfer all the three rings from A to C, we will first shift the upper two rings (n-1 rings) from the source pole to the spare pole. We move the first two rings from pole A to B as shown in Figure 4.13.
| | |
| | |
| ==|== |
======|====== ====|==== |
---------------------------------------------
A B C
Figure 4.13 Move rings from A to B
Now that n-1 rings have been removed from pole A, the n<sup>th</sup> ring can be easily moved from the source pole (A) to the destination pole (C). Figure 4.14 shows this step.
| | |
| | |
| ==|== |
| ====|==== ======|======
---------------------------------------------
A B C
Figure 4.14 Move rings from A to C
The final step is to move the n-1 rings from B to C using A as the spare pole. This is shown in Figure 4.15.
| | |
| | ==|==
| | ====|====
| | ======|======
---------------------------------------------
A B C
Figure 4.15 Move rings from B to C
To summarize, the solution to our problem of moving n rings from A to C using B as spare can be given as:
Base case: if n=1
Move the ring from A to C using B as spare
Recursive case:
Move n-1 rings from A to B using C as spare
Move the one ring left on A to C using B as spare
Move n-1 rings from B to C using A as spare
The following code implements the solution of the Tower of Hanoi problem.
#include <stdio.h>
void move(int, char, char, char);
int main()
{
int n;
printf("\n Enter the number of rings: ");
scanf("%d", &n);
move(n,'A', 'C', 'B');
return 0;
}
void move(int n, char source, char dest, char spare)
{
if (n==1)
printf("\n Move from %c to %c",source,dest);
else
{
move(n-1,source,spare,dest);
move(1,source,dest,spare);
move(n-1,spare,dest,source);
}
}
Let us look at the Tower of Hanoi problem in detail using the program given above. Figure 4.16 explains the working of the program using one, then two, and finally three rings.
Figure 4.16 Working of Tower of Hanoi with one, two, and three rings
One ring
| | |
==|== | |
---------------------------------------------
A B C
(Step 1)
| | |
| | ==|==
---------------------------------------------
A B C
(Step 2)
(If there is only one ring, then simply move the ring from source to the destination.)
Two rings
| | |
==|== | |
====|==== | |
---------------------------------------------
A B C
(Step 1)
| | |
| | |
====|==== ==|== |
---------------------------------------------
A B C
(Step 2)
| | |
| | |
| ==|== ====|====
---------------------------------------------
A B C
(Step 3)
| | |
| | ==|==
| | ====|====
---------------------------------------------
A B C
(Step 4)
(If there are two rings, then first move ring 1 to the spare pole and then move ring 2 from source to the destination. Finally move ring 1 from the spare pole to the destination.)
Three rings
| | |
==|== | |
====|==== | |
======|====== | |
---------------------------------------------
A B C
(Step 1)
| | |
| | |
====|==== | |
======|====== | ==|==
---------------------------------------------
A B C
(Step 2)
| | |
| | |
| | |
======|====== ====|==== ==|==
---------------------------------------------
A B C
(Step 3)
| | |
| | |
| ==|== |
======|====== ====|==== |
---------------------------------------------
A B C
(Step 4)
| | |
| | |
| ==|== |
| ====|==== ======|======
---------------------------------------------
A B C
(Step 5)
| | |
| | |
| | |
==|== ====|==== ======|======
---------------------------------------------
A B C
(Step 6)
| | |
| | |
| | ====|====
==|== | ======|======
---------------------------------------------
A B C
(Step 7)
| | |
| | ==|==
| | ====|====
| | ======|======
---------------------------------------------
A B C
(Step 8)
(Consider the working with three rings.)
4.13 RECURSION VERSUS ITERATION
Recursion is more of a top-down approach to problem solving in which the original problem is divided into smaller sub-problems. On the contrary, iteration follows a bottom-up approach that begins with what is known and then constructing the solution step by step.
Recursion is an excellent way of solving complex problems especially when the problem can be defined in recursive terms. For such problems, a recursive code can be written and modified in a much simpler and clearer manner.
However, recursive solutions are not always the best solutions. In some cases, recursive programs may require substantial amount of run-time overhead. Therefore, when implementing a recursive solution, there is a trade-off involved between the time spent in constructing and maintaining the program and the cost incurred in running-time and memory space required for the execution of the program.
Whenever a recursive function is called, some amount of overhead in the form of a run time stack is always involved. Before jumping to the function with a smaller parameter, the original parameters, the local variables, and the return address of the calling function are all stored on the system stack. Therefore, while using recursion a lot of time is needed to first push all the information on the stack when the function is called and then time is again involved in retrieving the information stored on the stack once the control passes back to the calling function.
To conclude, one must use recursion only to find solution to a problem for which no obvious iterative solution is known. To summarize the concept of recursion, let us briefly discuss the pros and cons of recursion.
The advantages of using a recursive program include the following:
Recursive solutions often tend to be shorter and simpler than non-recursive ones.
Code is clearer and easier to use.
Recursion works similar to the original formula to solve a problem.
Recursion follows a divide and conquer technique to solve problems.
In some (limited) instances, recursion may be more efficient.
The drawbacks/disadvantages of using a recursive program include the following:
For some programmers and readers, recursion is a difficult concept.
Recursion is implemented using system stack. If the stack space on the system is limited, recursion to a deeper level will be difficult to implement.
Aborting a recursive process in midstream can be a very slow process.
Using a recursive function takes more memory and time to execute as compared to its non-recursive counterpart.
It is difficult to find bugs, particularly while using global variables.
The advantages of recursion pays off for the extra overhead involved in terms of time and space required.
POINTS TO REMEMBER
Every function in a program is supposed to perform a well-defined task. The moment the compiler encounters a function call, the control jumps to the statements that are part of the called function. After the called function is executed, the control is returned back to the calling function.
All the libraries in C contain a set of functions that have been prewritten and pre-tested, which the programmers can use without worrying about the code details. This speeds up program development.
While function declaration statement identifies a function with its name, the list of arguments that it accepts and the type of data it returns, the function definition, on the other hand, consists of a function header that identifies the function, followed by the body of the function containing the executable code for that function.
main() is the function that is called by the operating system and, therefore, it is supposed to return the result of its processing to the operating system.
Placing the function declaration statement prior to its use enables the compiler to make a check on the arguments used while calling that function.
A function having void as its return type cannot return any value. Similarly, a function having void as its parameter list cannot accept any value.
When a function is defined, space is allocated for that function in the memory. A function definition comprises of two parts: function header and function body.
Call-by-value method passes values of the variables to the called function. Therefore, the called function uses a copy of the actual arguments to perform its intended task. This method is used when the function does not need to modify the values of the original variables in the calling function.
In call-by-reference method, address of the variables are passed by the calling function to the called function. Hence, in this method, a function receives an implicit reference to the argument, rather than a copy of its value. This allows the function to modify the value of the variable and that change will be reflected in the calling function as well.
Scope means the accessibility and visibility of the variables at different points in the program. A variable or a constant in C has four types of scope: block, function, program, and file scope.
Storage class defines the scope (visibility) and life time of variables and/or functions declared within a C program.
The auto storage class is the default storage class for variables declared inside a block. The scope of the variable is local to the block in which it is declared. When a variable is declared using register as its storage class, it is stored in a CPU register instead of RAM. Extern is used to give a reference of a global variable that is visible to all the program files. Static is the default storage class for global variables.
A recursive function is defined as a function that calls itself to solve a smaller version of its task until a final call is made which does not require a call to itself. Recursive functions are implemented using system stack.
GLOSSARY
Argument A value passed to the called function by the calling function
Block A sequence of definitions, declarations, and statements, enclosed within curly brackets.
Divide and conquer Solving a problem by dividing it into two or more smaller instances. Each of these smaller instances is recursively solved, and the solutions are combined to produce a solution for the original problem.
Iteration Solving a problem by repeatedly working on successive parts of the problem.
Recursion An algorithmic technique where a function calls itself with a smaller of the task in order to solve that task.
Recursion termination The point at which base condition is met and a recursive algorithm stops calling itself and begins to return values.
Recursion tree Technique to analyse the complexity of an algorithm by diagramming the recursive function calls.
Tail recursion A form of recursion in which the last operation of a function is a recursive call.
Tower of Hanoi Given three towers or poles and n disks of decreasing sizes, move the disks from one pole to another one by one without putting a larger disk on a smaller one.
EXERCISES
Fill in the Blanks
________ provides an interface to use the function.
After the function is executed, the control passes back to the ________.
A function that uses another function is known as the ________.
The inputs that the function takes are known as ________.
main() is called by the ________.
Function definition consists of ________ and ________.
In ________ method, address of the variable is passed by the calling function to the called function.
Function scope is applicable only within ________.
Function that calls itself is known as a ________ function.
Recursive functions are implemented using ________.
________ function is defined as a function that calls itself.
The function int func(); takes ________ arguments.
________ variables can be accessed from all functions in the program.
The execution of a program starts at ________.
By default, the return type of a function is ________.
Variable declared inside a function is known as ________.
Multiple Choice Questions
The function that is invoked is known as
(a) calling function
(b) caller function
(c) called function
(d) invoking function
Function declaration statement identifies a function with its
(a) name
(b) arguments
(c) data type of return value
(d) all of these
Which return type cannot return any value to the caller?
(a) int
(b) float
(c) void
(d) double
Memory is allocated for a function when the function is
(a) declared
(b) defined
(c) called
(d) returned
Which keyword allows a variable to have file scope?
(a) auto
(b) static
(c) register
(d) extern
The default storage class of global variables is
(a) auto
(b) static
(c) register
(d) extern
Which variable retains its value in-between function calls?
(a) auto
(b) static
(c) register
(d) extern
The default storage class of a local variable is
(a) auto
(b) static
(c) register
(d) extern
State True or False
The calling function must always pass parameters to the called function.
Function header is used to identify the function.
The name of a function is global.
No function can be declared within the body of another function.
The function call statement invokes the function.
Auto variables are stored inside CPU registers.
Extern variables are initialized by default.
The default storage class of local variables is extern.
Recursion follows a divide-and-conquer technique to solve problems.
Local variables overwrite the value of global variables.
A C function can return only one value.
A function must have at least one argument.
A function can be declared and defined before main().
A function can be defined in main().
Variable names in the function definition must match with those specified in the function declaration.
Specifying variable names in the function declaration is optional.
main() is a user-defined function.
Review Questions
Define a function. Why are they needed?
Explain the concept of making function calls.
Differentiate between function declaration and function definition.
Differentiate between formal parameters and actual parameters.
How many types of storage classes C language supports? Why do we need different types of such classes?
Give the features of each storage class.
Explain the concept of recursive functions with example.
Differentiate between an iterative function and a recursive function. Which one will you prefer to use and in what circumstances?
What will happen when the actual parameters are less than formal parameters in a function?
What will happen when data type of a variable in the function declaration does not match with the corresponding variable in the function header?
What will happen when a function returns a value that does not match with the return type of the function?
Explain the Tower of Hanoi problem.
Differentiate between call by value and call by reference using suitable examples.
What do you understand by scope of a variable? Explain in detail with suitable examples.
Why function declaration statement is placed prior to function definition?
Programming Exercises
Write a program to calculate factorial of a number using recursion. Also write a non-recursive function to do the same job.
Write a program using function that calculates the hypotenuse of a right-angled triangle.
Write a function that accepts a number n as input and returns the average of numbers from 1 to n.
Write a function to reverse a string using recursion.
Write a function is_prime that returns 1 if the argument passed to it is a prime number and a 0 otherwise.
Write a function that accepts an integer between 1 and 12 to represent the month number and displays the corresponding month of the year (For example if month = 1, then display JANUARY).
Write a function is_leap_year which takes the year as its argument and checks whether the year is a leap year or not and then displays an appropriate message on the screen.
Write a program to concatenate two strings using recursion.
Write a program to read an integer number. Print the reverse of this number using recursion
Write a program to swap two variables that are defined as global variables.
Write a program to compute F(x, y) where
F(x, y) = F(x-y, y) + 1 if y≤x
And F(x, y) = 0 if x<y
Write a program to compute F(n, r) where F(n, r) can be recursively defined as
F(n, r) = F(n-1, r) + F(n-1, r-1)
Write a program to compute Lambda(n) for all positive values of n where Lambda(n) can be recursively defined as
Lambda(n) = Lambda(n/2) + 1 if n>1
AND Lambda(n) = 0 if n=1
Write a program to compute F(M, N) where F(M, N) can be recursively defined as
F(M,N) = 1 if M=0 or M≥N≥1
AND F(M,N) = F(M-1,N) + F(M-1, N-1)
otherwise
Write a menu driven program to add, subtract, multiply, and divide two integers using functions.
Write a program to find the smallest of three integers using functions.
Write a program to calculate area of a triangle using function.
Write a program to find whether a number is divisible by two or not using functions.
Write a program to illustrate call-by-value technique of passing arguments to a function.
Write a program to illustrate call-by-reference technique of passing arguments to a function.
Write a program to swap two integers using call-by-value method of passing arguments to a function.
Write a program using function to calculate x to the power of y, where y can be either negative or positive.
Write a program using function to calculate compound interest given the principal, rate of interest, and number of years.
Write a program to swap two integers using call-by-reference method of passing arguments to a function.
Write a program to calculate factorial of a number (a) using recursion (b) without using recursion.
Write a program to convert the given string "hello world" to "dlrow olleh" without using recursion.
Write a program to find HCF of two numbers (a) using recursion (b) without using recursion.
Write a program to calculate x^y (a) using recursion (b) without using recursion.
Write a program to print the Fibonacci series (a) using recursion (b) without using recursion.
Write a program using functions to perform calculator operations.
Write a function that converts temperature given in Celsius into Fahrenheit.
Write a function that prints the conversion table of Degrees Fahrenheit into Degrees Celsius ranging from 32-212 degrees Celsius.
Write a function to draw the following pattern on the screen
********
! !
! !
! !
********
Write a program to print a table of binomial coefficients which is given by the formula-
#include <stdio.h>
int func();
main()
{
printf("%d", func());
printf("%d", func());
printf("%d", func());
printf("%d", func());
return 0;
}
int func()
{
int counter=0;
return counter;
}
2.
#include <stdio.h>
int func();
int counter = 5;
main()
{
printf("%d", func());
printf("%d", func());
printf("%d", func());
printf("%d", func());
return 0;
}
int func()
{
return counter++;
}
3.
#include <stdio.h>
int add(int, int);
main()
{
int a=2, b=3;
printf("%d %d %d", a, b, add(a, b));
return 0;
}
int add(int a, int b)
{
int c;
c = a+b;
}
4.
#include <stdio.h>
int func(int);
main()
{
int a=2;
printf("%d", func(a));
return 0;
}
int func(int a)
{
if(a>1)
return func(--a) + 10;
else
return 0;
}
#include <stdio.h>
int a;
static int func()
{
return a++;
}
main()
{
a=10;
printf("%d", func());
a *= 10;
printf("%d", func());
return 0;
}
11.
#include <stdio.h>
int prod(int x, int y)
{
return (x*y);
}
main()
{
int x=2, y=3, z;
z = prod(x,prod(x,y));
printf("%d", z);
return 0;
}
ANNEXURE 2
User Defined Header Files
At times programmers may need a function that provides additional processing capabilities and may want to create a separate source code file to contain that function. This would help to segregate the function from rest of the main source code. In such a situation, the user may create a user-defined header file so that the compiler knows how to call this function.
For example, if we want the factorial function to be stored in a user-defined header file, then write the code of the factorial function in a file and save it as "fact.h". Then in the main program file, we will include the fact.h file and call the function in the same way as we call other functions. Look at the code given below which illustrates this concept.
int factorial(int num)
{
long int f=1;
for(;num >= 1;num--)
f = f * num;
return f;
}
// Contents for the main file
#include <stdio.h>
#include"fact.h"
int main()
{
int num, f;
printf("\n Enter any numner: ");
scanf("%d", &num);
f = factorial(num);
printf("\n FACTORIAL of %d = %d", num, f);
return 0;
}
In the above code, a user-defined header file—fact.h has been used. The name of the header file has been enclosed within quotes to tell the compiler not to look along the standard library path, but to look in the same path as the source file.
When you compile the file that contains the source code, that is the file contains main(), the compiler will compile it into object code. As long as the C program is syntactically correct, the object code will be created.
The linker will combine the object code and library files, and create an executable file. It is the header file that links the definition of the function with the implementation.