0% found this document useful (0 votes)
23 views107 pages

DS Module1

Uploaded by

tupiprasanna1507
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views107 pages

DS Module1

Uploaded by

tupiprasanna1507
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 107

Array Continue

Algorithms for Traversing an Array


Algorithm 1: (Traversing a Linear Array) Here LA is a linear array with lower bound LB and
upper bound UB. This algorithm traverses LA applying an operation PROCESS
to each element of LA.
1. Set K:=LB.
2. Repeat Steps 3 and 4 while K<=UB
3. [Visit element.] Apply PROCESS to LA[K].
4. [Increase counter.] Set K:=K+1.
[End of Step 2 loop.]
5. Exit.

Algorithm 2: (Traversing a Linear Array) This algorithm traverses a linear array LA with lower
bound LB and upper bound UB.
1. Repeat for K=LB to UB
Apply PROCESS to LA[K].
[End of loop.]
2. Exit.

Algorithm for Inserting and Deleting an Element from an Array


Algorithm 3: (Inserting into a Linear Array) INSERT(LA, N, K, ITEM)
Here LA is a linear array with N elements and K is a positive integer such that
K<=N. This algorithm inserts an ITEM into the Kth position in LA.
1. [Initialize counter.] Set J:=N
2. Repeat Steps 3 and 4 while J>=K
3. [Move Jth element downward.] Set LA[J+1]:=LA[J].
4. [Decrease counter.] Set J:=J-1.
[End of Step 2 loop.]
5. [Insert element.] Set LA[K]:=ITEM.
6. [Reset N.] Set N:=N+1.
7. Exit.
Algorithm 4: (Deleting from a Linear Array) DELETE(LA, N, K, ITEM)
Here LA is a linear array with N elements and K is a positive integer such that
K<=N. This algorithm deetes the Kth element from LA.
1. [Initialize counter.] Set ITEM:=LA[K].
2. Repeat for J=K to N-1:
[Move (J+1) element upward.] Set LA[J]:=LA[J+1].
3. [Decrease counter.] Set J:=J-1.
[End of Step 2 loop.]
4. [Reset the number N of elements in LA.] Set N:=N-1.
5. Exit.

Algorithm for Sorting the Elements of an Array


Algorithm 5: (Bubble Sort) BUBBLE(DATA, N)
Here DATA is an array with N elements. This algorithm sorts the elements in
DATA.
1. Repeat Steps 2 and 3 K=1 to N-1
2. Set PTR:=1. [Initialize pass pointer PTR.]
3. Repeat while PTR<=N-K: [Execute pass.]
a. If DATA[PTR] > DATA[PTR+1], then:
Interchange DATA[PTR] and DATA[PTR+1].
[End of If structure.]
b. Set PTR:=PTR+1.
[End of inner loop.]
[End of Step 1outer loop.]
4. Exit.

Algorithms for Searching an Element of an Array


Algorithm 6: (Linear Search) LINEAR(DATA, N, ITEM, LOC)
Here DATA is a linear array with N elements, and ITEM is a given item of
information. This algorithm finds the location LOC of ITEM in DATA, or sets
LOC:=0 if the search is unsuccessful.
1. [Insert ITEM at the end of DATA.] Set DATA[N+1]:=ITEM.
2. [Initialize counter.] Set LOC:=1.
3. [Search for ITEM.]
Repeat while DATA[LOC] != ITEM:
Set LOC:=LOC+1.
[End of loop.]
4. [Successful?] If LOC=N+1, then: Set LOC :=0.
5. Exit.

Algorithm 7: (Binary Search) BINARY(DATA, LB, UB, ITEM, LOC)


Here DATA is a linear array with lower bound LB and upper bound UB, and ITEM
is a given item of information. The variables BEG, END and MID denote,
respectively, the beginning, end and middle locations of a segment of elements of
DATA. This algorithm finds the location LOC of ITEM in DATA or sets
LOC+NULL.
1. [Initialize segment variables.]
Set BEG:=LB, END:=UB and MID=INT((BEG+END)/2).
2. Repeat Steps 3 and 4 while BEG<=END and DATA[MID] != ITEM
3. If ITEM < DATA[MID], then
Set END:=MID - 1.
Else:
Set BEG:=MID+1.
[End of If structure.]
4. Set MID:=INT((BEG+END)/2).
[End of Step 2 loop.]
5. If DATA[MID] = ITEM, then:
Set LOC:=MID.
Else:
Set LOC:=NULL.
[End of If structure.]
6. Exit.
Insertion Operation
Insert operation is to insert one or more data elements into an array. Based on the requirement, a
new element can be added at the beginning, end, or any given index of array.
Example: Let la be a Linear Array (unordered) with n elements and k is a positive integer such
that k<=n. Following is the algorithm where item is inserted into the kth position of la.

#include <stdio.h>
main() Output:
Enter the number of array elements
{ 5
int la[25]; Enter the array elements
int item, k, n; 13578
int i, j = n; The original array elements are :
printf(“Enter the number of array elements\n”); la[0] = 1
scanf(“%d”,&n); la[1] = 3
printf(“Enter the array elements\n”); la[2] = 5
for(i=0;i<n;i++) la[3] = 7
{ la[4] = 8
scanf(“%d”,&la[i]); Enter the position and item to be inserted
} 3
printf("The original array elements are :\n"); 10
for(i = 0; i<n; i++) The array elements after insertion :
{ la[0] = 1
printf("la[%d] = %d \n", i, la[i]); la[1] = 3
} la[2] = 5
printf(“Enter the position and item to be inserted\n”); la[3] = 10
scanf(“%d%d”,&k,&item); la[4] = 7
n = n + 1; la[5] = 8
while( j >= k)
{
la[j+1] = la[j];
j = j - 1;
}
la[k] = item;
printf("The array elements after insertion :\n");
for(i = 0; i<n; i++)
{
printf("la[%d] = %d \n", i, la[i]);
}
}

Deletion Operation
Deletion refers to removing an existing element from the array and re-organizing all elements of
an array.
Example: Consider la is a linear array with n elements and k is a positive integer such that k<=n.
Following is the algorithm to delete an element available at the kth position of la.

#include<stdio.h>
main( )
{
int la[25];
int k, n;
int i, j;
printf(“Enter the number of array elements\n”);
scanf(“%d”,&n);
printf(“Enter the array elements\n”);
for(i=0;i<n;i++)
{
scanf(“%d”,&la[i]);
}
printf("The original array elements are :\n");
for(i = 0; i<n; i++)
{
printf("la[%d] = %d \n", i, la[i]); Output:
} Enter the number of array elements
printf(“Enter the position of element to be deleted\n”); 5
scanf(“%d”,&k); Enter the array elements
j = k; 13578
while( j < n) The original array elements are :
{ la[0] = 1
la[j-1] = la[j]; la[1] = 3
j = j + 1; la[2] = 5
} la[3] = 7
n = n -1; la[4] = 8
printf("The array elements after deletion:\n"); Enter the position of element to be deleted
for(i = 0; i<n; i++) 3
{ The array elements after deletion :
printf("la[%d] = %d \n", i, la[i]); la[0] = 1
} la[1] = 3
} la[2] = 7
la[3] = 8
Search Operation
Search’s for an array element based on its value or its index.
Example: Consider la is a linear array with n elements and k is a positive integer such that k<=n.
Following is the algorithm to find an element with a value of item using sequential search.

#include <stdio.h>
main( )
{
int la[25];
int item, n;
int i, j = 0,flag=0;
printf(“Enter the number of array elements\n”);
scanf(“%d”,&n);
printf(“Enter the array elements\n”);
Output:
for(i=0;i<n;i++)
Enter the number of array elements
{
5
scanf(“%d”,&la[i]);
Enter the array elements
}
1
printf("The original array elements are :\n");
3
for(i = 0; i<n; i++)
5
{
7
printf("la[%d] = %d \n", i, la[i]);
8
}
The original array elements are :
printf(“Enter the element to be searched\n”);
la[0] = 1
scanf(“%d”,&item);
la[1] = 3
while( j < n)
la[2] = 5
{
la[3] = 7
if( la[j] == item )
la[4] = 8
{
Enter the element to be searched
Flag=1;
5
break;
Found element 5 at position 3
}
j = j + 1;
}
if(flag)
printf("Found element %d at position %d\n", item, j+1);
else
printf("Element not found”);
}

Update Operation
Update operation refers to updating an existing element from the array at a given index.
Example: Consider la is a linear array with n elements and k is a positive integer such that k<=n.
Following is the algorithm to update an element available at the kth position of la.
#include<stdio.h>
Output:
main( ) Enter the number of array elements
{ 5
Enter the array elements
int la[25];
13578
int k, n, item; The original array elements are :
int i, j; la[0] = 1
printf(“Enter the number of array elements\n”); la[1] = 3
la[2] = 5
scanf(“%d”,&n); la[3] = 7
printf(“Enter the array elements\n”); la[4] = 8
for(i=0;i<n;i++) Enter the position and new value of element to
be updated
{
3
scanf(“%d”,&la[i]); 9
} The array elements after updation:
la[0] = 1
printf("The original array elements are :\n");
la[1] = 3
for(i = 0; i<n; i++) la[2] = 9
{ la[3] = 7
printf("la[%d] = %d \n", i, la[i]); la[4] = 8

}
printf(“Enter the position and new value of element to be updated\n”);
scanf(“%d%d”,&k,&item);
la[k-1] = item;
printf("The array elements after updation:\n");
for(i = 0; i<n; i++)
{
printf("la[%d] = %d \n", i, la[i]);
}
}
Sorting
Ordering of elements of an array in either ascending or descending sequence is termed as sorting.
Example: Program to print the elements of array in ascending and descending order.
#include <stdio.h>
int main( )
{
Output:
int a[10], i=0, j=0, n, t;
Enter the no. of elements: 5
printf ("\n Enter the no. of elements: ");
Enter the 1th element: 25
scanf ("%d", &n);
Enter the 2th element: 50
printf ("\n");
Enter the 3th element: 75
for (i = 0; i <n; i++)
Enter the 4th element: 35
{
Enter the 5th element: 100
printf ("\n Enter the %dth element: ", (i+1));
Ascending order: 25 35 50 75 100
scanf ("%d", &a[i]);
Descending order: 100 75 50 35 25
}
for (j=0 ; j<(n-1) ; j++)
{
for (i=0 ; i<(n-1) ; i++)
{
if (a[i+1] < a[i])
{
t = a[i];
a[i] = a[i + 1];
a[i + 1] = t;
}
}
}
printf ("\n Ascending order: ");
for (i=0 ; i<n ; i++)
{
printf (" %d", a[i]);
}
printf ("\n Descending order: ");
for (i=n ; i>0 ; i--)
{
printf (" %d", a[i-1]);
}
/* indicate successful completion */
return 0;
}

Example: Program for generating Fibonacci series using array


/*Program for generating Fibonacci series using array*/
#include<stdio.h>
#include<conio.h>
void main()
{
int fib[20],n,i;
Output:
printf(“Enter Number of terms to be generated\n”);
Enter the number of terms to be generated
scanf(“%d”,&n);
7
fib[0] = 0;
Fibonacci Series
fib[1] = 1;
0112358
printf(“Fibonacci Series\n”);
for(i=2 ; i<n ; i++)
{
fib[i] = fib[i-1] + fib[i-2];
}
for(i=0 ; i<n ; i++)
{
printf(“%d\t”,fib[i]);
}
getch( ); }
Strings Continue....
Data Structures and Applications {BCS304} Module-1: Introduction

String Manipulation Functions

String Functions Description


strlen(str_name); This function returns the length of the string
This function copies the string from one variable to
strcpy(destination_str,source_str);
another variable
This function also copies the string from one variable
strncpy(destination_str,source_str,length);
to another variable, but only upto the specified length
This function is used to compare two strings. They are
strcmp(string1,string2);
case sensitive.
This function is also used to compare two strings, but
stricmp(string1,string2);
they are not case sensitive.
This function compares two strings only upto a
strncmp(string1,string2,length);
specified length. They are case sensitive.
This function also compares two strings only upto a
strnicmp(string1,string2,length);
specified length, but not case sensitive.
This function converts upper case character to lower
strlwr(string_name);
case.
This function converts lower case character to upper
strupr(string_name);
case.
strcat(string1,string2); This function is used to concatenate (join) two strings.
This function is used to reverse the characters in a given
strrev(string_name);
string.
This function replaces all the characters of a string with
strset(string,symbol);
a given symbol or character.
This function also replaces all the characters of a string
strnset(string,symbol,length); with a given symbol or character but only to a specified
length.
strstr(string_name, pattern); Return pointer to start of pattern in string string_name

Dept. of CSE, RNSIT 34


Data Structures and Applications {BCS304} Module-1: Introduction

strlen( ):
/*Illustrating string length function i.e strlen( ) */
#include<stdio.h>
#include<conio.h>
#include<string.h>
main( ) Output:
{ Enter a string:Sahyadri
char a[30]; Length of sting is 8
int l;
printf(“Enter a string”);
scanf(“%s”,a);
l=strlen(a);
printf(“\n Length of string is %d\n”,l);
getch( );
}

strcpy( ):
/*Program to illustrate strcpy( ) function*/
#include<stdio.h>
#include<string.h>
Outpt:
main( )
Enter a string PCD
{
Value of a PCD
char a[10],b[10];
Value of b PCD
printf(“Enter a string\n”);

scanf(“%s”,a);
strcpy(b,a);
printf(“Value of a:%s\n”,a);
printf(“Value of b:%s\n”,b);
}

Dept. of CSE, RNSIT 35


Data Structures and Applications {BCS304} Module-1: Introduction

strncpy( ):
/*Program to illustrate strcpy( ) */
#include<stdo.h>
#include<string.h> Output:
main( ) Enter a string :yuvraj
{ Value of a :yuvraj
char a[10],b[10]; Value of b :yuv
printf(“Enter a string\n”);
scanf(“%s”,a);
strncpy(b,a,3);
printf(“Value of a: %s\n”,a);
printf(“Value of b: %s\n”,b);
}

strcmp( ):
/* Program to illustrate strcmp( ) function*/
#include<stdio.h>
#include<string.h>
main()
{
char a[10],[10];
int n;’
printf(“Enter string one:\n”); Output:
scanf(“%s”,a); Enter string one :dravid
printf(“Enter string two\n”); Enter string two :dravid
scanf(“%s”,b); Both strings are equal
n=strcmp(a,b);
if(n==0)
{
printf(“Both strings are equal\n”);

Dept. of CSE, RNSIT 36


Data Structures and Applications {BCS304} Module-1: Introduction

}
else
{
printf(“Strings are not equal”);
}
}

stricmp( ):
/*Program to illustrate stricmp( ) fuction*/
#include<stdio.h>
#include<conio.h>
#include<strings>
main( )
{
char a[30],b[30];
int n; Output:
printf(“Enter string one :”); Enter string one :raydu
scanf(“%s”,a); Enter string two :RAYDU
printf(“Enter string two:”);
Both strings are equal
scanf(“%s”,b);
n=stricmp(a,b);
if(n==0)
{
printf(“Both strings are equal\n”);
}
else
{
printf(“Strings are not equal\n”);
getch( );
}

Dept. of CSE, RNSIT 37


Data Structures and Applications {BCS304} Module-1: Introduction

strncmp( ):
/* Program to illustrate strcmp( ) function*/
#include<stdio.h>
#include<conio.h>
#include<strings>
void main( )
{ Output :
char a[30],b[30]; Enter string one: ragav
int n; Enter string two: ragev
printf(“Enter string one:”); Both strings are equal upto 3 characters
scanf(“%s”,a);
printf(“Enter string two:”);
scanf(“%s”,b);
n=strncmp(a,b,2);
if(n==0)
{
printf(“Both strings are equal up to 2 characters”);
}
else
{
printf(“Strings are not equal”);
}
getch();
}

strnicmp( ):
/* Program to illustrate strnicmp() function*/
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()

Dept. of CSE, RNSIT 38


Data Structures and Applications {BCS304} Module-1: Introduction

{
Output:
char a[30],b[30];
Enter string one:devi
int n;
Enter string two:debi
printf(“Enter string one:”);
Both strings are equal upto first 2 characters
scanf(“%s”,a);
printf(“Enter string two:”);
scanf(“%s”,b);
n=strnicmp(a,b,2);
if(n==0)
{
printf(“Both strings are wqual upto first 2 characters”);
}
else
{
printf(“Strings are not equal”);
}
getch();
}

strlwr( ):
/*Program to illustrate strlwr() function*/
#include<stdio.h> Output:

#include<string.h> Enter a string in uppercase :DEVI

main() Final string is :devi

{
char a[30];
printf(“Enter a string in upper case:\n”);
scanf(“%s”,a);
printf(“Final string is:%s”,strlwr(a));
}

Dept. of CSE, RNSIT 39


Data Structures and Applications {BCS304} Module-1: Introduction

strupr( ):
/*Program to illustrate strupr() function*/
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main() Output:
{ Enter a string in lowercase :kohli
char a[30]; Final string is :KOHLI
printf(“Enter a string in lowercase:”);
scanf(“%s”,a);
printf(“Final string is :%s”,strupr(a));
getch();
}

strcat( ):
/*Program to illustrate strcat() fuctions*/
#include<stdio.h>
#include<conio.h>
#include<string.h>
Output:
main()
Enter string one:Prakhyath
{
Enter string two:Rai
char a[30],b[30];
Final string is:PrakhyathRai
printf(“Enter string one:”);
scanf(“%s”,a);
printf(“Enter string two:”);
scanf(“%s”,b);
strcat(a,b);
printf(“Final string is:%s”,a);
getch();
}

Dept. of CSE, RNSIT 40


Data Structures and Applications {BCS304} Module-1: Introduction

strrev():
/*Program to illustrate strrev() fuctions*/
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char a[30]; Output:
printf(“Enter string:”); Enter string:Prakhyath
scanf(“%s”,a); Reversed string is:htayhkarP
strrev(a);
printf(“Reversed string :%s”,a);
getch( );
}

strset( ):
/*Program to illustrate strset() fuctions*/
#include<stdio.h>
#include<conio.h>
Output:
#include<string.h>
Enter a string:Vikhyath
main( )
Enter a symbol to replace the string:#
{
After strset:########
char a[30];
char b;
printf(“Enter a string:”);
gets(a);
printf(“Enter a symbol to replace the string:”);
scanf(“%c”,&b);
strset(a,b);
printf(“After strset:%s”,a);
getch();

Dept. of CSE, RNSIT 41


Data Structures and Applications {BCS304} Module-1: Introduction

strnset( ):
/*Program to illustrate strnset() fuctions*/
#include<stdio.h>
#include<conio.h>
#include<string.h> Output:
main( ) Enter a string:Vikhyath
{ Enter a symbol to replace the string:#
char a[30]; After strnset:###hyath
char b;
printf(“Enter a string:”);
scanf(“%s”,a);
printf(“Enter a symbol to replace the string:”);
scanf(“%c”,&b);
strnset(a,b,3);
printf(“After strnset:%s”,a);
getch();
}

Example: Program to sort the strings in alphabetical order


/*Program to sort strings in alphabetical order*/
#include<stdio.h>
#include<conio.h>
#include<string.h>
main( )
{
char str[20][25],temp[25];
int i,j,n;
printf(“How Many Strings”);

Dept. of CSE, RNSIT 42


Data Structures and Applications {BCS304} Module-1: Introduction

scanf(“%d”,&n);
for(i=0;i<n;i++)
Output:
{
How Many Strings
printf(“Enter string %d”,i+1);
5
scanf(“%s”,str[i]);
Enter string 1
}
Ajay
for(i=0;i<n-1;i++)
Enter string 2
{
Vicky
for(j=0;j<(n-1-i);j++)
Enter string 3
{
Bharath
if(strcmp(str[j],str[j+1])>0)
Enter string 4
{
Rahul
strcpy(temp,str[j]);
Enter string 5
strcpy(str[j],str[j+1]);
Chethan
strcpy(str[j+1],temp);
Sorted strings are:
}
Ajay
}
Bharath
}
Chethan
printf(“Sorted strings are :\n”);
Rahul
for(i=0;i<n;i++)
Vicky
{
printf(“%s\n”,str[i]);
}
}

Dept. of CSE, RNSIT 43


Data Structures and Applications {BCS304} Module-1: Introduction

Pattern Matching
Assume two strings, string and pat, where pat is a pattern to be searched for in string. The built-
in function strstr can be used to perform this operation.
char pat[MAX_SIZE], string[MAX_SIZE], *t;
The built in function strstr is illustrated as follows,

if( t = strstr(string, pat))

printf(“The string from strstr is: %s\t”,t);

else

printf(“The pattern was not found with strstr\n”);


The call (t = strstr(string,pat)) returns a null pointer if pat is not in string. If pat is in string, t
holds a pointer to the start of pat in string. The entire string beginning at position t is printed out.
Techniques to improve pattern matching,
 By quitting when strlen(pat) is greater than the number of remaining characters in the string.
 Checking the first and last characters of pat and string before we check the remaining
characters.

Pattern Matching by Checking End Indices First


int nfind(char *string, char *pat)
{/* match the last character of pattern first, and then match from the beginning */
int i, j,start=0;
int lasts =strlen(string)-1;
int lastp=strlen(pat)-1;

int endmatch=lastp;

for(i=0; endmatch <= lasts; endmatch++, start++)


{

if(string[endmatch]==pat[latp])
for(j=0,i=start;j<lastp && string[i] == pat[j]; i++,j++)
;

Dept. of CSE, RNSIT 99


Data Structures and Applications {BCS304} Module-1: Introduction

if(j== lastp)
return start; /*successful */

}
return -1;
}

Kruth, Morris, Pratt Pattern Matching Algorithm


#include<stdio.h>
#include<string.h>

#define max_string_size 100


#define max_pattern_size 100
int pmatch( );

void fail( );
int failure[max_pattern_size];
char string[max_string_size];

char pat[max_pattern_size];

int pmatch(char *string, char *pat)


{/*Knuth, Morris, Pratt string matching algorithm*/
int i=0, j=0;
int lens = strlen(string);
int lenp = strlen(pat);
while(i<lens && j<lenp)

{
if(string[i] == pat[j])
{
i++;

Dept. of CSE, RNSIT 100


Data Structures and Applications {BCS304} Module-1: Introduction

j++;
}

else if(j==0)
i++;
else

j=failure[j-1]+1;
}
return (j == lenp) ? (i-lenp) : -1);

void fail(char *pat)

{/*Compute the pattern’s failure function */


int n = strlen(pat);
failure[0] = -1;
for(j=1; j<n; j++)

{
i = failure[i];
while((pat[j] !=pat[i+1]) && (i>=0))
i=failure[i];
if(par[j]==pat[i+1])
failure[j]=i+1;
else failure[j] = -1;

}
}

Dept. of CSE, RNSIT 101


NOTE: C program to evaluate suffix/postfix expression:(refer lab-program-5a)

Recursion:
Recursion is the name given for expressing anything in terms of itself.
A function which contains a call to itself or call to another function ,which eventually causes the first
function to be called,is known as a recursive function.
 Recursive procedures generally solve a given problem by reducing the problem to an instance of the
same problem with smaller input.
 Once the function is called an activation record is created on the stack
 Call to it self is repeated till a base condition is reached.
 Once a base condition or terminal condition is reached,the function returns the result to previous copy
of the function.
 A sequence of returns ensures that the solution to the original problem obtained.

The recursive procedure(function) must have the following properties.


 There must be certain condition ,called base condition,for which the procedure(function) does not call
itself.
 Each time the procedure(function) does call itself (directly or indirectly),it must be closer to the base
condition.

Examples for recursive function.


1. Factorial function
The product of the positive integers from 1 to n,inclusive,is called “n factorial” and is usually
denoted by n!.

n!=1.2.3…..(n-2)(n-1)n.
Recursive procedure to find the factorial of N.(algorithm)

FACTORIAL(N,FACT)
1. IF N=0,then:Set Fact:=1 and return
2 call FACTORIAL(N-1,FACT);
3. Set FACT:= N*FACT;
4. return.

Recursive function in C
int fact(int n)
{
If(n==0)
return 1;
return (n*fact(n-1));
}
Note: Write a iterative function(by using loop) to find factorial of n.

2. Fibonacci Sequence:

The fibonacci sequence is series of terms where each suceeding term is a sum of two preceding
terms.
0,1,1,2,3,5,8……
Here,F0=0, F1=1.
F3=F0+F1=0+1=2
Similarly, Fn=Fn-2+Fn-1
Recursive Procedure to find fibanocci sequence.
FIBONACCI(FIB,N)
1)If N=0 or N=1,then :Set FIB:=N, and Return
2)Call FIBONACCI(FIBA,N-2).
3) Call FIBONACCI(FIBB,N-1).
4) Set FIB:=FIBA+FIBB.
5) Return.

Recursive function in C to find nth fibonacci number

int fibonacci(int n)
{
if(n==0)
return 0;
if(n==1)
return 1;
return (fibonacci(n-2)+fibonacci(n-1));
}
Note: Write a iterative function(by using loop) to generate n fibanocci sequence.
3. Ackermann function.
 It is a non primitive or nested recursive function.(a primitive recursive is a one which can be
implemented by using loops ex: factorial,GCD etc.)
 In computability theory, the Ackermann function, named after Wilhelm Ackermann
 Main use of Ackermann function is in mathematical logic
 It is one of the classical example for recursion.
 After Ackermann's publication of his function (which had three nonnegative integer
arguments), many authors modified it to suit various purposes, so that today "the Ackermann
function" may refer to any of numerous variants of the original function. One common version, the
two-argument is defined as follows for nonnegative integers m and n:

Ackermann function. A(m,n)


1)A(m,n)=n+1, when m=0
2)A(m,n)=A(m-1,1), when m>0, n=0
3) A(m,n)=A(m-1, A(m,n-1)) when m>0 and n>0

Ackermann function in C
int acker(int m,int n)
{
if(m==0)
return n+1;
else if(m>0&&n==0)
return acker(m-1,1);
else return acker(m-1,acker(m,n-1));
}

What is the value of A(1,3)?

4. Tower of Hanoi:-

 It is a popular game
 It is one of the best example how recursion used as tool in developing an algorithm to solve a
particular problem.
 Consider 3 pegs A , B & C & suppose on peg A there are placed a finite number n of disks
with decreasing order
Rules
1) Only one disk may be moved at a time
2) At no time can a larger disk be placed on a smaller disk
• For n=3 : AC ,AB ,CB , AC, BA, BC, AC
• For completeness ,we also give the solution to the Towers of Hanoi problem for n=1 & n=2
n=1 : AC (one move)
n=2 : AB , AC , BC (3 moves)
Technique of recursion to develop a general solution
1. Move the top n-1 disks from peg A to peg B
2. Move the top disk from peg A to peg C
3. Move the top n-1 disks from peg B to peg C

Recursive procedure to Tower of Hanoi:- TOWER(N,BEG,AUX,END)


1. When n=1,then
a. TOWER(1, BEG,AUX,END) or Write:= BEGEND
b. return
2. When n>1

a. TOWER(N-1,BEG,END,AUX) [ Move the top n-1 disks from peg A to peg B]


b. TOWER(1, BEG,AUX,END) or Write:- BEGEND

c. TOWER(N-1,AUX,BEG,END) [Move the top n-1 disks from peg B to peg C ]


C program to Tower of Hanoi
#include<stdio.h>
#include<conio.h>
int tower(int n,char beg,char aux,char end)
{
if(n==1)
{
printf("thed disk 1 is move from %c to %c\n",beg,end);
return;
}
tower(n-1,beg,end,aux);
printf("the disk %d is moved from %c to %c\n",n,beg,end);
tower(n-1,aux,beg,end);
}
void main()
{
int num;
printf("enter the number of disk \n");
scanf("%d",&num);
tower(num,'A','B','C');
getch();
}

GCD recursive function:[


int gcd(int n1, int n2)
{
if (n2!=0)
return gcd(n2, n1%n2);
else
return n1;
}

You might also like