You are on page 1of 19

FIBONACCI USING 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);
}
}

FACTORIAL USING RECURSION


#include<stdio.h>
int fact(int);
int main(){
int num,f;
printf("\nEnter a number: ");
scanf("%d",&num);
f=fact(num);
printf("\nFactorial of %d is: %d",num,f);
return 0;
}
int fact(int n){
if(n==1)
return 1;
else
return(n*fact(n-1));
}

FIBONACCI WITHOUT USING 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 %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--;
}
}

C Function Arguments & No Return Value

Function with arguments and no Return Value :

Note :

Function accepts argument but it does not return a value back to the calling Program .

It is Single ( One-way) Type Communication

Generally Output is printed in the Called function

Here area is called function and main is calling function.

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

Passing Argument to Function :


1. In C Programming we have different ways of parameter passing schemes such as Call by Value and
Call by Reference.
2. Function is good programming style in which we can write reusable code that can be called whenever
require.
3. Whenever we call a function then sequence of executable statements gets executed. We can pass some
of the information to the function for processing called argument.

Two Ways of Passing Argument to Function in C Language :


1. Call by Reference
2. Call by Value

Let us discuss different ways one by one

A.Call by Value :
#include<stdio.h>

void interchange(int number1,int number2)


{
int temp;
temp = number1;
number1 = number2;
number2 = 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 : 50
Number 2 : 70

Explanation : Call by Value


1. While Passing Parameters using call by value , xerox copy of original parameter is created and
passed to the called function.
2. Any update made inside method will not affect the original value of variable in calling function.
3. In the above example num1 and num2 are the original values and xerox copy of these values is passed
to the function and these values are copied into number1,number2 variable of sum function
respectively.

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>

void interchange(int *num1,int *num2)


{
int temp;
temp

= *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

Explanation : Call by Address


1. While passing parameter using call by address scheme , we are passing the actual address of the
variable to the called function.
2. Any updates made inside the called function will modify the original copy since we are
directly modifying the content of the exact memory location.

Summary of Call By Value and Call By Reference :


Point

Call by Value

Call by Reference

Copy

Duplicate Copy of Original


Parameter is Passed

Actual Copy of Original Parameter is


Passed

Modification

No effect on Original Parameter


after modifying parameter in
function

Original Parameter gets affected if


value of parameter changed inside
function

C Formal Vs Actual Parameters

What is Parameter ?

In C Programming Function Passing Parameter is Optional.

We can Call Function Without Passing Parameter .

Function With Parameter :


add(a,b);

1. Here Function add() is Called and 2 Parameters are Passed to Function.


2. a,b are two Parameters.

Function Call Without Passing Parameter :


Display();

What is Actual Definition of Parameter ?


In computer programming, a parameter is a special kind of variable, used in a subroutine
to refer to one of the pieces of data provided as input to the subroutine.These pieces o
f data are called arguments. [Definition From Wiki]
Note :

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.

4. Syntactically We can pass any number of parameter to function.


5. Parameters are Specified Within Pair of Parenthesis .
6. These Parameters are Separated by Comma (,)

Display(a,b,c,d,e);

Parameter :

The names given in the function definition are called Parameters.

Argument

The values supplied in the function call are called Arguments.

Formal Parameter :

Parameter Written In Function Definition is Called Formal Parameter.

void main()
{
int num1;
display(num1);
}
void display(int para1)
{
--------------------}

Para1 is Formal Parameter

Actual Parameter :

Parameter Written In Function Call is Called Actual Parameter.

void main()
{
int num1;
display(num1);
}

void display(int para1)


{
--------------------}

num1 is Actual Parameter

Passing Arrays as Function Arguments in C


Advertisements

Previous Page
Next Page

If you want to pass a single-dimension array as an argument in a function, you


would have to declare function formal parameter in one of following three ways
and all three declaration methods produce similar results because each tells the
compiler that an integer pointer is going to be received. Similar way you can pass
multi-dimensional array as formal parameters.

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;

for (i = 0; i < size; ++i)


{
sum += arr[i];
}

avg = sum / size;

return avg;
}

Now, let us call the above function as follows:


#include <stdio.h>

/* 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;

/* pass pointer to the array as an argument */


avg = getAverage( balance, 5 ) ;

/* output the returned value */


printf( "Average value is: %f ", 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)

printf("\n This is a recursive function \n");

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

This is a recursive function

This is a recursive function

....

....

This is a recursive function

This is a recursive function

This is a recursive function

Segmentation fault (core dumped)

In the output above:

The print This is a recursive function prints continuously many times.

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 :

For each call to func(), a new function stack is created.

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.

2. Practical Example of C Recursion


For complete newbies, it ok to have a question like Whats the practical use of recursion? In this
section, I will provide some practical examples where recursion can makes things really easy.
Suppose you have numbers from 0 to 9 and you need to calculate the sum of these numbers in
the following way :

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;

void func(int sum)

sum

= sum + count;

count ++;

if(count <= 9)

func(sum);

else

printf("\nSum is [%d] \n", sum);

return;

int main(void)

int sum = 0;

func(sum);

return 0;

If you try to understand what the above code does, you will observe :

When func() was called through main(), sum was zero.

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 func(int num)

int res = 0;

if(num <= 0)

printf("\n Error \n");

else if(num == 1)

return num;

else

res

= num * func(num -1);

return res;

return -1;

int main(void)

int num = 5 ;

int fact

= func(num);

if (fact > 0)

printf("\n The factorial of [%d] is [%d]\n", num, fact);

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

= 5 * func(5 -1); // This is func() stack 1

res

= 4 *func(4-1);

// This is func() stack 2

res

= 3 *func(4-1);

// This is func() stack 3

res

= 2 *func(2-1);

// This is func() stack 4

return 1;

// This is func() stack 5

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

The factorial of [5] is [120]

You might also like