FCS Module-3 Notes[Arrays]
FCS Module-3 Notes[Arrays]
Introduction:
2. Multi-dimensional array
data_type array_name[size];
Here,
A is the array
k is the index of the element of which we have to calculate the address
BA is the base address of the array A.
w is the word size of one element in memory, for example, size of int is 2.
Example 1:
Given an array int marks[ ]={99,67,78,56,88,90,34,85}. Calculate the address
of marks[4] if base address=1000.
Address(Marks[4])=1000+2(4-0)// size of int=2
=1000+2*4
=1000+8
=1008
Example 2:
Given an array float avg[ ]={99.0,67.0,78.0,56.0,88.0,90.0,34.0,85.0}. Calculate
the address of avg[4] if base address=1000.
Address(Avg[4]) =1000+4(4-0)// size of float=4
=1000+4*4
=1000+16
=1016
Length=Upper_bound-Lower_bound+1
=4-0+1=5
Storing values in an Array
{
scanf("%d",&a[i]);
}
for(i=0;i<5;i++)
{
printf("Array a[%d]=%d\n",i,a[i]);
}
}
Output:
Enter the elements: 1 2 3 4 5
Array a[0]=1
Array a[1]=2
Array a[2]=3
Array a[3]=4
Array a[4]=5
2. WAP to search an element in an array.
#include<stdio.h>
void main()
{
int i,a[20],n,key;
printf("Enter the number of elements: ");
scanf("%d",&n);
printf("Enter the elements: ");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Enter the key element to be searched: ");
scanf("%d",&key);
for(i=0;i<n;i++)
{
Dr Santhosh Kumar S, Jain University, Bengaluru Page 5
Module-3: Arrays, Strings and Functions
if(key==a[i])
printf("Element found at position %d\n",i+1);
}
}
Output:
Enter the number of elements: 5
Enter the elements: 1 2 3 4 5
Enter the key element to be searched: 5
Element found at position 5
3. WAP to print the position of smallest of numbers using array.
#include<stdio.h>
void main()
{
int i,a[20],n,small,pos;
printf("Enter the number of elements: ");
scanf("%d",&n);
printf("Enter the elements: ");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
small=a[0];
pos=0;
for(i=0;i<n;i++)
{
if(a[i]<small)
{
small=a[i];
pos=i;
}
}
printf("The smallest element is %d and the position is %d",small,pos+1);
}
Output:
Enter the number of elements: 5
Enter the elements: 2 3 4 5 6
The smallest element is 2 and the position is 1
Operations on array
1. Traversing an array
2. Inserting an element in an array
3. Deleting an element from an array
4. Merging 2 arrays
5. Searching an element in an array
6. Sorting an array in ascending or descending order
1. Traversing an array
• Traversing an array means accessing each and every element of the array
for a specific purpose.
Algorithm for Array Traversal:
Step 1: [Initialization] SET I=lower_bound
Step 2: Repeat steps 3 and 4 while I<=upper_bound
Step 3: Apply process to A[I]
Step 4: Set I=I+1;
Step 5: Exit
2. Inserting an element in an array
• Inserting an element in an array means adding a new data element to an
already existing array.
Algorithm to insert a new element to the end of the array:
Step 1: Set upper_bound= upper_bound+1//Increment the value of Upper
bound
Step 2: Set A[upper_bound]= VAL(Value that has to be inserted]//New value is
Dr Santhosh Kumar S, Jain University, Bengaluru Page 7
Module-3: Arrays, Strings and Functions
stored
Step 3: EXIT
Algorithm to insert a new element in middle of the array:
Step 1: Set I=N//N=Number of elements
Step 2: Repeat 3 and 4 while I>=POS//POS=position at which element has to
be inserted
Step 3: Set A[I+1]=A[I]
Set A[I+1]=A[I]
Step 4: Set N=N+1
Step 5: Set A[POS]=VAL
Step 6: EXIT
4. WAP to insert a number at a given location in an array.
#include<stdio.h>
void main()
{ int i,a[20],n,num,pos;
printf("Enter the number of elements: ");
scanf("%d",&n);
printf("Enter the elements: ");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Enter the number to be inserted: ");
scanf("%d",&num);
printf("Enter the postion at which number has to be inserted: ");
scanf("%d",&pos);
for(i=n-1;i>=pos;i--)
a[i+1]=a[i];
a[pos]=num;
n++;
printf("The array after insertion of %d is :",num);
Dr Santhosh Kumar S, Jain University, Bengaluru Page 8
Module-3: Arrays, Strings and Functions
for(i=0;i<n;i++)
printf("\t%d",a[i]);
}
Output:
Enter the number of elements: 5
Enter the elements: 1 2 4 5 6
Enter the number to be inserted: 3
Enter the postion at which number has to be inserted: 2
The array after insertion of 3 is : 1 2 3 4 5 6
n--;
printf("The array after deletion is :");
for(i=0;i<n;i++)
printf("\nA[%d]=%d",i,a[i]);
}
Output:
Enter the number of elements: 5
Enter the elements: 1 2 3 4 5
Enter the postion from which number has to be deleted: 4
The array after deletion is :
A[0]=1
A[1]=2
A[2]=3
A[3]=4
7. WAP to delete a number from an array that is already sorted in
ascending order
#include<stdio.h>
void main()
{
int i,n,j,num,a[10];
printf("Enter the number of elements: ");
scanf("%d",&n);
printf("Enter the elements: ");
for(i=0;i<n;i++)
{ scanf("%d",&a[i]); }
printf("Enter the number to be deleted: ");
scanf("%d",&num);
for(i=0;i<n;i++)
{
if(a[i]==num)
{
for(j=i;j<n-1;j++)
a[j]=a[j+1];
}
}
printf("The array after deletion is");
for(i=0;i<n-1;i++)
printf("\t%d",a[i]);
Dr Santhosh Kumar S, Jain University, Bengaluru Page 11
Module-3: Arrays, Strings and Functions
}
Output:
Enter the number of elements: 5
Enter the elements: 1 2 3 4 5
Enter the number to be deleted: 3
The array after deletion is 1 2 4 5
Merging 2 arrays
• Merging of 2 arrays in a third array means first copying the contents of
the first array into the third array and then copying the contents of
second array into the third array.
• Hence, the merged array contains contents of the second array.
{
a3[index]=a1[index_1];
index_1++;
}
else
{
a3[index]=a2[index_2];
index_2++;
}
index++;
}
if(index_1==n1)//if elements of the first array are over and the second array
has some elements
{
while(index_2<n2)
{
a3[index]=a2[index_2];
index_2++;
index++;
}
}
else if(index_2==n2) //if elements of the second array are over and the
first array has some elements
{
while(index_1<n1)
{ a3[index]=a1[index_1];
index_1++;
index++;
}
printf("\n\nThe contenets of merged array are");
for(i=0;i<m;i++)
printf("\n Arr[%d] = %d",i,a3[i]);
}
Output:
Enter the number of elements in array1:3
Enter the elements in array1:4 5 6
Enter the number of elements in array2:3
Enter the elements in array2:1 2 3
The contenets of merged array are
Arr[0] = 1
Arr[1] = 2
Arr[2] = 3
Arr[3] = 4
Arr[4] = 5
Arr[5] = 6
• If the value is not present, the search process displays the appropriate
message.
Linear search: ALGORITHM
Step1: [Initialization] Set pos=-1
Step2: [Initialization] Set I=0
Step3: Repeat Step 4 while I<=N
Step4: IF A[I]= val
SET POS=I
PRINT POS
Go to Step 6
[END OF IF]
SET I=I+1
[END OF LOOP]
Step5: IF POS= -1,
PRINT “VALUE IS NOT PRESENT IN THE ARRAY”
[END OF IF]
Step6: EXIT
9. Program:
#include<stdio.h
> void main()
{
int a[10],num,i,n,found=0,pos=-1;
printf("Enter the number of elements in an array: ");
scanf("%d",&n);
printf("Enter the elements: ");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the number that has to be searched: ");
scanf("%d",&num);
for(i=0;i<n;i++)
{
if(a[i]==num)
{
found=1;
pos=i;
printf("\n%d is found in the array at position %d",num,i+1);
break;
}
Dr Santhosh Kumar S, Jain University, Bengaluru Page 15
Module-3: Arrays, Strings and Functions
}
if(found==0)
printf("Element not found in the array");
}
Output:
Enter the number of elements in an array: 5
Enter the elements: 50 9 6 7 1
Enter the number that has to be searched: 6
6 is found in the array at position 3
}
else if(a[mid]<key)
low=mid+1;
else
high=mid-1;
}
if(low>high)
printf("%d not found in the array",key);
}
Output:
Enter the number of elements in an array: 5
Enter the elements: 1 2 3 4 5
Enter the value to find: 3 3 found at location 3
11. WAP to sort n numbers in ascending order using bubble sort technique:
#include<stdio.h>
void main()
{ int i,j,n,temp,a[20];
printf("Enter the number of elements in an array: ");
scanf("%d",&n);
printf("Enter the elements: ");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1-i;j++)
{
if(a[j]>a[j+1])
{ temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("Array after implementing bubble sort:");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
}
Output:
Enter the number of elements in an array: 5
Enter the elements: 60 9 8 5 100
Array after implementing bubble sort: 5 8 9 60 100
12. WAP to sort n numbers in descending order using bubble sort technique:
#include<stdio.h>
void main()
{
int i,j,n,temp,a[20];
printf("Enter the number of elements in an array: ");
scanf("%d",&n);
printf("Enter the elements: ");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1-i;j++)
{
if(a[j]<a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
2-Dimensional Array
int a[2][3]={1,2,3,4,5,6}
int a[2][3]={{1,2,3},{4,5,6}}
3. Partial initialization
int a[2][3]={{1,1},{2}}
int a[ ][3]={{1,2,3},{4,5,6}}
for(i=0;i<row;i++)
for(j=0;j<column;j++)
{
scanf(“%d”,&a[i][j]);
}
printf("The array elements are:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
}
Output:
Enter the number of rows and columns: 3,3
Enter the elements of the array:1 2 3 4 5 6 7 8 9
The array elements are:
1 2 3
4 5 6
7 8 9
14. WAP to generate Pascal’s triangle.
#include<stdio.h>
void main()
{
int a[5][5]={0},row=2,col,i,j;
a[0][0]=a[1][0]=a[1][1]=1;
while(row<5)
{
a[row][0]=1;
for(col=1;col<=row;col++)
a[row][col]=a[row-1][col-1]+a[row-1][col];
row++;
}
for(i=0;i<5;i++)
{
printf("\n");
for(j=0;j<=i;j++)
printf("%d\t",a[i][j]);
}
}
Output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("The array elements are:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
b[i][j]=a[j][i];
}
}
printf("The elemnts of transposed matrix are:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t",b[i][j]);
}
printf("\n");
}
Output:
Enter the number of rows and columns: 3,3
Enter the elements of the array:1 2 3 4 5 6 7 8 9
The array elements are:
1 2 3
4 5 6
7 8 9
1 4 7
2 5 8
3 6 9
16. WAP to input 2 m x n matrices and then calculate the sum of their
corresponding elements and store it in third m x n matrix.
#include<stdio.h
void main()
{ int a[20][20],b[20][20],c[20][20],m,n,p,q,r,t,i,j;
printf("Enter the number of rows and columns in first matrix: ");
scanf("%d,%d",&m,&n);
printf("Enter the number of rows and columns in second matrix: ");
scanf("%d,%d",&p,&q);
if(m!=p||n!=q)
{
printf("Number of rows and columns of both the matrix should be
equal");
}
r=m;
t=n;
printf("Enter the elements of the array 1:");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
}
printf("The elements of the resultant matrix are:\n");
for(i=0;i<r;i++)
{ for(j=0;j<t;j++)
{ printf("%d\t",c[i][j]);
}
printf("\n");
}
}
Output:
4 4
4 4
17. WAP to input 2 m x n matrices and then calculate the product of their
corresponding elements and store it in third m x n matrix.
#include<stdio.h>
void main()
{
int a[20][20],b[20][20],c[20][20],m,n,p,q,k,i,j;
printf("Enter the number of rows and columns in first matrix: ");
scanf("%d,%d",&m,&n);
printf("Enter the number of rows and columns in second matrix: ");
scanf("%d,%d",&p,&q);
if(n!=p)
{
printf("Matrix multiplication is not possible");
}
printf("Enter the elements of the array 1:");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter the elements of the array 2:");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
c[i][j]=0;
for(k=0;k<n;k++)
c[i][j]=a[i][k]*b[k][j]+c[i][j];
}
}
printf("The elements of the resultant matrix are:\n");
for(i=0;i<m;i++)
for(j=0;j<q;j++)
printf("%d\t",c[i][j]);
}
printf("\n");
}}
Output:
number of rows and columns in second matrix: 2,2 Enter the elements of
8 8
8 8
#include<stdio.h> void
square(int x);
void main()
int n,a[10],i;
scanf("%d",&n);
for(i=0;i<n;i++) scanf("%d",&a[i]);
for(i=0;i<n;i++)
square(a[i]);
void square(int x)
{
printf("%d\t",x*x); return;
Output:
elements: 1 2 3 4 5
void main()
int b[6]={1,2,3,4,5,6};
avg(b);
sum=sum+a[i];
Average=sum/6; printf("Average=%d",Average);
Output:
Average=3
Multi-Dimensional array
• Like we have 1 index in 1-D array, 2 index in 2-D array, we have n index in n-
dimensional array.
Output:
is:
a[0][0][0]=1 a[0][0][1]=2
a[0][1][0]=3 a[0][1][1]=4
a[1][0][0]=5 a[1][0][1]=6
a[1][1][0]=7 a[1][1][1]=8
Applications of array
• Storing and accessing data: Arrays are used to store and retrieve data in a
specific order. For example, an array can be used to store the scores of a group of
students, or the temperatures recorded by a weather station.
• Sorting: Arrays can be used to sort data in ascending or descending order. Sorting
algorithms such as bubble sort, merge sort, and quick sort rely heavily on arrays.
• Stacks and queues: Arrays are used as the underlying data structure for
implementing stacks and queues, which are commonly used in algorithms and
data structures.
Strings:-
Definition:- A string constant or a string literal can be defined as a sequence of characters enclosed
in double quotes that will be treated as a single data element followed by a null character ‘\0’
Syntax: char string_name[size];
Where, char is the data type of strings
string_name is a valid identifier which is the name for the string variable
size indicates the length of the string which is to be stored
Initialization of strings:
char str1[10]= “peter”; or
char str1[10]={‘p’,‘e’,‘t’,‘e’,‘r’};
Both the initializations mentioned are same, if we directly specify the entire string at a time we use “
”
Formatted input and output:-
scanf() and printf():-
The scanf() and printf()statements are used when we are reading or displaying a single string
(without space).
We do not use “&” symbol in scanf because string name itself represent the address where it is to be
stored.
%s is the format specifier used for string.
21. C program to read and display string using formatted I/O function */
#include<stdio.h>
void main()
{
char str[20];
printf(“Enter a string\n”);
scanf(“%s”,str);
printf(“The entered string is =%s\n”,str);
}
String Copy:- The function strcpy() copies the content from one string to another string
SYNTAX : strcpy(str2,str1);
String Concatenate :- The function strcat() is used to concatenate (attach) two strings.
SYNTAX : strcat(str1,str2);
string str2 is attached to the end of string str1
29. C program to concatenate two strings using strcat function */
#include<stdio.h>
#include<string.h>
void main()
{
char str1[30],str2[30];
printf("Enter String1\n");
scanf("%s",str1);
printf("Enter String2\n");
scanf("%s",str2);
strcat(str1,str2);
printf("The concatenated string is=%s\n",str1);
}
***** OUTPUT ***** Harry
Enter String2 Potter
The characters from left to right in the original string are placed in the reverse order
SYNTAX : strrev(str1)
30. C program to reverse a string using strrev( ) function */
#include<stdio.h>
#include<string.h>
void main()
char str1[30];
printf("Enter String1\n");
gets(str1);
strrev(str1);
#include<stdio.h>
#include<string.h>
void main()
{ char str1[50],str2[50];
int i,j,len,x;
printf("Enter String1\n");
gets(str1);
j=0;
len=strlen(str1);
for(i=len-1;i>=0;i--)
{
str2[j]=str1[i]; j++;
}
str2[j]='\0';
x=strcmp(str1,str2);
if(x==0)
printf("%s is a palindrome\n",str1);
else
malayalam is a palindrome
String Lower :- The function strlwr() converts each character of the string to lowercase.
SYNTAX : strlwr(string_data);
String Upper :- The function strupr() converts each character of the string to uppercase.
SYNTAX : strupr(string_data);
32. C program to convert strings to uppercase and lowercase using strupr( ) and strlwr ( )
functions*/
#include<stdio.h>
#include<string.h>
void main()
{ char str1[50],str2[50];
scanf("%s",str1);
The string in Upper case letter is= DUMBLEDORE Enter the string in Upper case letters
HAGRID
33. C program to count the number of Vowels and Consonants in a given Sentence */
#include<stdio.h>
#include<string.h>
#include<ctype.h>
main()
char str1[50],ch;
int i,vc=0,cc=0,ac=0,ec=0,ic=0,oc=0,uc=0;
gets(str1);
puts(str1);
for (i=0;i<strlen(str1);i++)
if(isalpha(str1[i]))
ch=str1[i]; if(ch=='a'||ch=='A')
ac++;
else if(ch=='e'||ch=='E')
ec++;
else if(ch=='i'||ch=='I')
ic++;
else if(ch=='o'||ch=='O')
oc++;
else if(ch=='u'||ch=='U')
uc++;
else
cc++;
vc=ac+ec+ic+oc+uc;
FUNCTIONS
➢ A function as series of instructions or group of statements with one specific purpose.
➢ A function is a program segment that carries out some specific, well-defined task.
➢ A function is a self contained block of code that performs a particular task.
4.1 Types of functions
➢ C functions can be classified into two types,
1. Library functions /pre-defined functions /standard functions /built in functions
2. User defined functions
1. Library functions /pre-defined functions /standard functions/Built in Functions
➢ These functions are defined in the library of C compiler which are used frequently in the
C program.
➢ These functions are written by designers of c compiler.
➢ C supports many built in functions like
• Mathematical functions
• String manipulation functions
• Input and output functions
• Memory management functions
• Error handling functions
EXAMPLE:
• pow(x,y)-computes xy
• sqrt(x)-computes square root of x
• printf()- used to print the data on the screen
• scanf()-used to read the data from keyboard.
2. User Defined Functions
➢ The functions written by the programmer /user to do the specific tasks are called user
defined function(UDF’s).
➢ The user can construct their own functions to perform some specific task. This type of
functions created by the user is termed as User defined functions.
2. Function Declaration
➢ The process of declaring the function before they are used is called as function
declaration or function prototype.
➢ function declaration Consists of the data type of function, name of the function
and parameter list ending with semicolon.
3. Function Call:
➢ The method of calling a function to achieve a specific task is called as function
call.
➢ A function call is defined as function name followed by semicolon.
➢ A function call is nothing but invoking a function at the required place in the
program to achieve a specific task.
Ex:
void main()
{
add( ); // function call without parameter
}
✓ In this category, there is data transfer from the calling function to the called
function using parameters.
✓ But there is no data transfer from called function to the calling function.
✓ The values of actual parameters m and n are copied into formal parameters a and b.
✓ The value of a and b are added and result stored in sum is displayed on the screen
in called function itself.
3. Function with no parameters and with return values
Calling function Called function
add();
{
void main()
{ int a,b,sum;
} return sum;
}
✓ In this category there is no data transfer from the calling function to the
called function.
✓ But, there is data transfer from called function to the calling function.
✓ No arguments are passed to the function add( ). So, no parameters are defined
in the function header
✓ When the function returns a value, the calling function receives one value
from the called function and assigns to variable result.
✓ The result value is printed in calling function.
4. Function with parameters and with return values
Calling function Called function
✓ In this category, there is data transfer between the calling function and called
function.
✓ When Actual parameters values are passed, the formal parameters in called
function can receive the values from the calling function.
✓ When the add function returns a value, the calling function receives a value from
the called function.
✓ The values of actual parameters m and n are copied into formal parameters a and
b.
✓ Sum is computed and returned back to calling function which is assigned to
variable result.
4.3 Passing parameters to functions or Types of argument passing
The different ways of passing parameters to the function are:
✓ Pass by value or Call by value
✓ Pass by address or Call by address
1. Call by value:
➢ In call by value, the values of actual parameters are copied into formal parameters.
➢ The formal parameters contain only a copy of the actual parameters.
➢ So, even if the values of the formal parameters changes in the called function, the
values of the actual parameters are not changed.
➢ The concept of call by value can be explained by considering the following program.
Example:
#include<stdio.h>
scanf("%d %d",&m,&n);
printf("the values before swapping are m=%d n=%d \n",m,n);
swap(m,n);
printf("the values after swapping are m=%d n=%d \n",m,n);
}
➢ Execution starts from function main( ) and we will read the values for variables m
and n, assume we are reading 10 and 20 respectively.
➢ We will print the values before swapping it will print 10 and 20.
➢ The function swap( ) is called with actual parameters m=10 and n=20.
➢ In the function header of function swap( ), the formal parameters a and b
receive the values 10 and 20.
➢ In the function swap( ), the values of a and b are exchanged.
➢ But, the values of actual parameters m and n in function main( ) have not been
exchanged.
➢ The change is not reflected back to calling function.
2. Call by Address
➢ In Call by Address, when a function is called, the addresses of actual
parameters are sent.
➢ In the called function, the formal parameters should be declared as pointers
with the same type as the actual parameters.
➢ The addresses of actual parameters are copied into formal parameters.
➢ Using these addresses the values of the actual parameters can be changed.
➢ This way of changing the actual parameters indirectly using the addresses of
actual parameters is known as pass by address.
Example:
#include<stdio.h>
void swap(int a,int b); void
main()
{ int m,n;
printf("enter values for a and b:");
scanf("%d %d",&m,&n);
printf("the values before swapping are m=%d n=%d \n",m,n);
swap(&m,&n);
printf("the values after swapping are m=%d n=%d \n",m,n);
}
}
Pointer: A pointer is a variable that is used to store the address of another variable.
Syntax:
datatype *variablename;
Example: int *p;
#include<stdio.h>
void main()
{
int a ,*p;
p=&a;
}
In the above program p is a pointer variable, which is storing the address of variable a.
EX:
#include<stdio.h>
main()
{
int
m=1000;
func2();
} printf(“%d\n”,m);
func1()
{
int m=10;
} printf(“%d\n”,m);
➢ The static variables can be declared outside the function and inside the
function. They have the characteristics of both local and global variables.
➢ Static can also be defined within a function.
Ex: static int a,b;
#include<stdi
o.h> main()
{
int I;
for (I=1;I<=3;I++)
stat();
}
stat()
{
static
int
x=0;
x=x+1;
printf(“x=%d\n”,x);
}
iv. Register variables
Recursion
➢ Recursion is a method of solving the problem where the solution to a problem
depends on solutions to smaller instances of the same problem.
➢ Recursive function is a function that calls itself during the execution.
➢ Consider Example for finding
factorial of 5 Factorial(5)=n*fact(n-1)
34. Factorial of a given number using Recursion
#include<stdio.h>
int fact(int n);
void main( )
{
int num,result;
printf("enter
number:");
scanf("%d",&num
);
result=fact(num);
printf("The factorial of a number is: %d",result);
}
int fact(int n)
{
if(n==0)
r
etur
n 1;
else
return (n*fact(n-1));
}
Output :
enter number:5
The factorial of a number is:120
Fibonacci Sequence:
The Fibonacci Sequence is the series of numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
The next number is found by adding up the two numbers before it.
• The 2 is found by adding the two numbers before it (1+1)
• The 3 is found by adding the two numbers before it (1+2),
• And the 5 is (2+3),
• and so on!
Example 2.
/******* Fibonacci of a given number using Recursion ******/
#include<stdio.h>
int fibonacci(int);
void main ()
{
int n,f;
printf("Enter the value of n?");
scanf("%d",&n);
f = fibonacci(n);
printf("%d",f);
}
int fibonacci (int n)
{
if (n==0)
{
return 0;
}
else if (n == 1)
{
return 1;
}
else
{
return fibonacci(n-1)+fibonacci(n-2);
}
}