Functions and Recursion
Functions and Recursion
#include<stdio.h>
void printFibonacci(int);
int main(){
int k,n;
long int i=0,j=1,f;
printf("Enter the range of the Fibonacci series: ");
scanf("%d",&n);
printf("Fibonacci Series: ");
printf("%d %d ",0,1);
printFibonacci(n);
return 0;
}
void printFibonacci(int n){
static long int first=0,second=1,sum;
if(n>0){
sum = first + second;
first = second;
second = sum;
printf("%ld ",sum);
printFibonacci(n-1);
}
}
#include<stdio.h>
void printFibonacci(int);
int main(){
int k,n;
long int i=0,j=1,f;
printf("Enter the range of the Fibonacci series: ");
scanf("%d %d ",&n);
printf("Fibonacci Series: ");
printf("%d ",0);
printFibonacci(n);
return 0;
}
void printFibonacci(int n){
long int first=0,second=1,sum;
while(n>0){
sum = first + second;
first = second;
second = sum;
printf("%ld ",sum);
n--;
}
}
Note :
Function accepts argument but it does not return a value back to the calling Program .
Program :
#include<stdio.h>
#include<conio.h>
//---------------------------------------void area(float rad);
// Prototype Declaration
//---------------------------------------void main()
{
float rad;
printf("nEnter the radius : ");
scanf("%f",&rad);
area(rad);
getch();
}
//---------------------------------------void area(float rad)
{
float ar;
ar = 3.14 * rad * rad ;
printf("Area of Circle = %f",ar);
}
Output :
Enter the radius : 3
Area of Circle = 28.260000
C parameter passing
A.Call by Value :
#include<stdio.h>
int main() {
int num1=50,num2=70;
interchange(num1,num2);
printf("\nNumber 1 : %d",num1);
printf("\nNumber 2 : %d",num2);
return(0);
}
Output :
Number 1 : 50
Number 2 : 70
4. As their scope is limited to only function so they cannot alter the values inside main function.
B.Call by Reference/Pointer/Address :
#include<stdio.h>
= *num1;
*num1 = *num2;
*num2 = temp;
}
int main() {
int num1=50,num2=70;
interchange(&num1,&num2);
printf("\nNumber 1 : %d",num1);
printf("\nNumber 2 : %d",num2);
return(0);
}
Output :
Number 1 : 70
Number 2 : 50
Call by Value
Call by Reference
Copy
Modification
What is Parameter ?
1. Parameter Means Values Supplied to Function so that Function can Utilize These Va
lues.
2. Parameters are Simply Variables.
3.
Difference between Normal Variable and Parameter is that These Arguments are De
fined at the time of Calling Function.
Display(a,b,c,d,e);
Parameter :
Argument
Formal Parameter :
void main()
{
int num1;
display(num1);
}
void display(int para1)
{
--------------------}
Actual Parameter :
void main()
{
int num1;
display(num1);
}
Previous Page
Next Page
Way-1
Formal parameters as a pointer as follows. You will study what is pointer in next
chapter.
void myFunction(int *param)
{
.
.
.
}
Way-2
Formal parameters as a sized array as follows:
void myFunction(int param[10])
{
.
.
.
}
Way-3
Formal parameters as an unsized array as follows:
void myFunction(int param[])
{
.
.
.
}
Example
Now, consider the following function, which will take an array as an argument
along with another argument and based on the passed arguments, it will return
average of the numbers passed through the array as follows:
double getAverage(int arr[], int size)
{
int
i;
double avg;
double sum;
return avg;
}
/* function declaration */
double getAverage(int arr[], int size);
int main ()
{
/* an int array with 5 elements */
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
return 0;
}
When the above code is compiled together and executed, it produces the following
result:
Average value is: 214.400000
As you can see, the length of the array doesn't matter as far as the function is
concerned because C performs no bounds checking for the formal parameters.
1. C Recursion Concept
Lets start with a very basic example of recursion :
#include <stdio.h>
void func(void)
func();
return;
int main(void)
func();
return 0;
In the code above, you can see that the function func(), in its definition calls itself. So, func()
becomes a recursive function. Can you guess what will happen when the code (shown above) is
executed? If we go by the code, the main() function would call func() once and then func()
would continue calling itself forever. Will this be the exact behaviour?
Lets execute the code and check this. Here is the output :
$ ./recrsn
....
....
A set of three dots is used to omit large part of actual output which was nothing but the
same print.
Towards the end of the output you cab observe Segmentation fault or as we popularly say,
the program crashes.
Earlier, we thought that the program would continue executing forever because recursive
function func() would continue calling itself forever but it did not happen so. The program
crashed. Why did it crash?
Here is the reason for this crash :
With func() calling itself continuously, new function stacks also are also created
continuously.
At one point of time, this causes stack overflow and hence the program crashes.
On a related note, it is also important for you to get a good understanding onBuffer Over
Flow and Linked Lists.
0 + 1 = 1
1 + 2
= 3
3 + 3 = 6
6 + 4 = 10
10 + 5 = 15
15 + 6 = 21
21 + 7
=28
28 + 8 = 36
36 + 9 = 45
So, you can see that we start with 0 and 1, sum them up and add the result into next number ie 2
then again we add this result to 3 and continue like this.
Now, I will show you how recursion can be used to define logic for this requirement in a C code :
#include <stdio.h>
int count = 1;
sum
= sum + count;
count ++;
if(count <= 9)
func(sum);
else
return;
int main(void)
int sum = 0;
func(sum);
return 0;
If you try to understand what the above code does, you will observe :
For every call to func(), the value of sum is incremented with count (which is 1 initially),
which itself gets incremented with every call.
The condition of termination of this recursion is when value of count exceeds 9. This is
exactly what we expect.
When count exceeds 9, at this very moment, the value of sum is the final figure that we
want and hence the solution.
Here is another example where recursion can be used to calculate factorial of a given number :
#include <stdio.h>
int res = 0;
if(num <= 0)
else if(num == 1)
return num;
else
res
return res;
return -1;
int main(void)
int num = 5 ;
int fact
= func(num);
if (fact > 0)
return 0;
Please note that I have used hard coded number 5 to calculate its factorial. You can enhance
this example to accept input from user.
The earlier example demonstrated only how at the final call of func() sum was calculated but the
reason I used example is because it demonstrates how return values can be used produced
desired results. In the example above, the call sequence across different function stacks can be
visualized as :
res
res
= 4 *func(4-1);
res
= 3 *func(4-1);
res
= 2 *func(2-1);
return 1;
Now, substitute return value of stack 5 in stack 4, the return value of stack 4 (ie res) into stack 3
and so on. Finally, in stack 1 you will get something like
res = 5 * 24
This is 120, which is the factorial of 5, as shown in the output when you execute this recursive
program.
$ ./recrsn