0% found this document useful (0 votes)
6 views

FCS Module-3 Notes[Arrays]

Module-3 covers arrays, strings, and functions, explaining the definition, types, and operations on arrays, including declaration, address calculation, initialization, and various algorithms for insertion, deletion, and merging. It provides examples of C code for reading, writing, searching, and manipulating arrays. The module emphasizes the importance of understanding array operations for effective programming.

Uploaded by

daksh.yagya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

FCS Module-3 Notes[Arrays]

Module-3 covers arrays, strings, and functions, explaining the definition, types, and operations on arrays, including declaration, address calculation, initialization, and various algorithms for insertion, deletion, and merging. It provides examples of C code for reading, writing, searching, and manipulating arrays. The module emphasizes the importance of understanding array operations for effective programming.

Uploaded by

daksh.yagya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

Module-3: Arrays, Strings and Functions

Introduction:

• An array is a collection of items of same data type stored at contiguous


memory locations.

• Array of character is a string.

• Each data item of an array is called an element.

• And each element is unique and located in separated memory location.

• Each of elements of an array share a variable but each element having


different index no. known as subscript.
Any element in an array can be accessed using

1. Name of the array

2. Position of the element in an array.

There are 2 types of arrays

1. Single dimensional array

2. Multi-dimensional array

Declaration of 1-Dimensional arrays

• Arrays are declared using following syntax:

data_type array_name[size];

where, type can be int, float or char.


name is the name of the array.
size indicates number of elements in the array.

Example: int marks[10];

Calculating the address of Array

• Address of data element, A[k] = BA(A) + w(k – lower_bound)

Dr Santhosh Kumar S, Jain University, Bengaluru Page 1


Module-3: Arrays, Strings and Functions

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

Calculating the length of Array


Length of the array is given by:
Length= upper_bound - lower_bound+1
where

Dr Santhosh Kumar S, Jain University, Bengaluru Page 2


Module-3: Arrays, Strings and Functions

Upper_bound=index of the last element


Lower_bound=index of the first element
Usually Lower_bound is zero but this is not a compulsion.
Example 3:
Let Age[5] be Age[0]=2, Age[1]=5, Age[2]=3, Age[3]=1, Age[4]=7.

Length=Upper_bound-Lower_bound+1
=4-0+1=5
Storing values in an Array

Initialization can be done using the following syntax:


type array_name[size]={list of values};
1. Initializing all specified memory location:
int a[5]={10,20,30,40,50}

2. Partial array initialization


int a[5]={10,20}

Dr Santhosh Kumar S, Jain University, Bengaluru Page 3


Module-3: Arrays, Strings and Functions

3. Array initialization without size:


int a[ ]={10,20,30,40,50}

4. Array initialization without elements


int a[5]={0}

Inputting values from keyboard


int i, marks[10];
for(i=0;i<10;i++)
scanf(“%d”, &marks[i]);
Assigning values to Individual Elements
int i, arr1[10], arr2[10];
arr1[i]={0,1,2,3,4,5,6,7,8,9};
for(i=0;i<10;i++)
arr2[i] = arr1[i];
1. WAP to read and write one dimensional array.
#include<stdio.h>
void main()
{
int i,a[5];
printf("Enter the elements: ");
for(i=0;i<5;i++)

Dr Santhosh Kumar S, Jain University, Bengaluru Page 4


Module-3: Arrays, Strings and Functions

{
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;

Dr Santhosh Kumar S, Jain University, Bengaluru Page 6


Module-3: Arrays, Strings and Functions

}
}
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

5. WAP to insert a number in 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 inserted: ");
scanf("%d",&num);
for(i=0;i<n;i++)
{ if(a[i]>num)
{ for(j=n-1;j>=i;j--)
a[j+1]=a[j];
a[i]=num;
break;
}
}
n++;
printf("The array after insertion of %d is: ",num);
for(i=0;i<n;i++)
printf("\t%d",a[i]);

Dr Santhosh Kumar S, Jain University, Bengaluru Page 9


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 inserted: 0
The array after insertion of 0 is: 0 1 2 3 4 5
Deleting an element in an array
• Deleting an element from an array means removing a data element from
an already existing array.
Algorithm to delete a new element to the end of the array:
Step 1: Set upper_bound= upper_bound-1
Step 2: EXIT
Algorithm to delete element from middle of the array:
Step 1: Set I=POS// POS=position at which element has to be deleted
Step 2: Repeat 3 and 4 while I<=N-1//N=Number of elements in the array
Step 3: Set A[I] = A[I+1]
Step 4: Set I=I+1
Step 5: Set N=N-1
Step 6: EXIT
6. WAP to delete a number from a given location in an array.
#include<stdio.h>
void main()
{ int i,a[20],n,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 postion from which number has to be deleted: ");
scanf("%d",&pos);
for(i=pos;i<n-1;i++)
a[i]=a[i+1];
Dr Santhosh Kumar S, Jain University, Bengaluru Page 10
Module-3: Arrays, Strings and Functions

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.

8. WAP to merge 2 sorted arrays.


#include <stdio.h>
void main()
{
int a1[10],a2[10],a3[10],i,n1,n2,m,index=0,index_1=0,index_2=0;
printf("Enter the number of elements in array1:");
scanf("%d",&n1);
printf("Enter the elements in array1:");
for(i=0;i<n1;i++)
scanf("%d",&a1[i]);
printf("Enter the number of elements in array2:");
scanf("%d",&n2);
printf("Enter the elements in array2:");
for(i=0;i<n2;i++)
scanf("%d",&a2[i]);
m=n1+n2;
while(index_1<n1&&index_2<n2)
{
if(a1[index_1]<a2[index_2])

Dr Santhosh Kumar S, Jain University, Bengaluru Page 12


Module-3: Arrays, Strings and Functions

{
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++;

Dr Santhosh Kumar S, Jain University, Bengaluru Page 13


Module-3: Arrays, Strings and Functions

}
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

Searching for a value in an array

• Searching means to find whether a particular value is present in the


array or not.

• If the value is present in the array then search is said to be successful


and the search process gives the location of that array.

• 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

Dr Santhosh Kumar S, Jain University, Bengaluru Page 14


Module-3: Arrays, Strings and Functions

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

10. Binary Search:


#include<stdio.h>
void main()
{
int i,low,high,mid,n,key,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]);
printf("Enter the value to find: ");
scanf("%d",&key);
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(a[mid]==key)
{
printf("%d found at location %d",key,mid+1);
break;
Dr Santhosh Kumar S, Jain University, Bengaluru Page 16
Module-3: Arrays, Strings and Functions

}
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;

Dr Santhosh Kumar S, Jain University, Bengaluru Page 17


Module-3: Arrays, Strings and Functions

}
}
}
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;
}

Dr Santhosh Kumar S, Jain University, Bengaluru Page 18


Module-3: Arrays, Strings and Functions
}
}
printf("Array after implememting 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: 90 7 6 100 99
Array after implememting bubble sort: 100 99 90 7 6

2-Dimensional Array

Arrays with 2 dimensions are called 2 –Dimensional array or 2-D array.

Declaration of 2-D array:


data_type array_name[row_size][column_size];

data_type can be any primitive data type.

array_name is a variable name

row_size is the maximum number of rows in the array.

column_size is the maximum number of column in the array.

Example: int a[2][3];

This can be read as

Initialization of 2-D array:

1. Initialize with total number of elements:

int a[2][3]={1,2,3,4,5,6}

2. Initialize with sets


Dr Santhosh Kumar S, Jain University, Bengaluru Page 19
Module-3: Arrays, Strings and Functions

int a[2][3]={{1,2,3},{4,5,6}}

3. Partial initialization

int a[2][3]={{1,1},{2}}

4. Initialize without size

int a[ ][3]={{1,2,3},{4,5,6}}

Initialization of 2-D array:

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

for(j=0;j<column;j++)
{

scanf(“%d”,&a[i][j]);

13. WAP to read and display elements from 2-D array.


#include<stdio.h>
void main()
{
int a[20][20],m,n,i,j;
printf("Enter the number of rows and columns: ");
scanf("%d,%d",&m,&n);
printf("Enter the elements of the array:");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}

Dr Santhosh Kumar S, Jain University, Bengaluru Page 20


Module-3: Arrays, Strings and Functions

}
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++;

Dr Santhosh Kumar S, Jain University, Bengaluru Page 21


Module-3: Arrays, Strings and Functions

}
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

Operations on 2-Dimensional Array


1. Transpose
2. Sum
3. Difference
4. Product
15. WAP to transpose 3 X 3 matrix.
#include<stdio.h>
void main()
{
int a[20][20],m,n,i,j,b[20][20];
printf("Enter the number of rows and columns: ");
scanf("%d,%d",&m,&n);
printf("Enter the elements of the array:");
for(i=0;i<m;i++)

Dr Santhosh Kumar S, Jain University, Bengaluru Page 22


Module-3: Arrays, Strings and Functions

{
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

Dr Santhosh Kumar S, Jain University, Bengaluru Page 23


Module-3: Arrays, Strings and Functions

The elemnts of transposed matrix are:

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("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<r;i++)
{ for(j=0;j<t;j++)
{
c[i][j]=a[i][j]+b[i][j];
}

Dr Santhosh Kumar S, Jain University, Bengaluru Page 24


Module-3: Arrays, Strings and Functions

}
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:

Enter the number of rows and columns in first matrix: 2,2

Enter the number of rows and columns in second matrix: 2,2

Enter the elements of the array 1:2 2 2 2

Enter the elements of the array 2:2 2 2 2

The elements of the resultant matrix are:

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++)
{

Dr Santhosh Kumar S, Jain University, Bengaluru Page 25


Module-3: Arrays, Strings and Functions

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:

Dr Santhosh Kumar S, Jain University, Bengaluru Page 26


Enter the number of rows and columns in first matrix: 2,2 Enter the

number of rows and columns in second matrix: 2,2 Enter the elements of

the array 1:2 2 2 2

Enter the elements of the array 2:2 2 2 2 The elements

of the resultant matrix are:

8 8

8 8

Using arrays with functions

• Putting individual elements of the array

• Passing the whole array

18. Passing individual elements of the array

#include<stdio.h> void

square(int x);

void main()

int n,a[10],i;

printf("Enter the number of elements: ");

scanf("%d",&n);

printf("Enter the elements: ");

for(i=0;i<n;i++) scanf("%d",&a[i]);

printf("The square of given elements are: ");

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

square(a[i]);

void square(int x)
{

printf("%d\t",x*x); return;

Output:

Enter the number of elements: 5 Enter the

elements: 1 2 3 4 5

The square of given elements are: 1 4 9 16 25

19. Passing whole array


#include<stdio.h>
void avg(int a[]);

void main()

int b[6]={1,2,3,4,5,6};

avg(b);

void avg(int a[])

int i,Average,sum=0; for(i=0;i<6;i++)

sum=sum+a[i];

Average=sum/6; printf("Average=%d",Average);

Output:

Average=3
Multi-Dimensional array

• A Multi-Dimensional array is an array of arrays.

• Like we have 1 index in 1-D array, 2 index in 2-D array, we have n index in n-
dimensional array.

20. WAP to read and display 2 x 2 x 2 array.


#include<stdio.h> void
main()
{ int a[2][2][2],i,j,k;
printf("Enter the elements of the matrix: "); for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
for(k=0;k<2;k++)
{
scanf("%d",&a[i][j][k]);
}}
}
printf("The matrix is: \n"); for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
for(k=0;k<2;k++)
{
printf("a[%d][%d][%d]=%d\t",i,j,k,a[i][j][k]);
}
printf("\n");
}
}}

Output:

Enter the elements of the matrix: 1 2 3 4 5 6 7 8 9 The matrix

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.

• Searching: Arrays can be searched for specific elements using


algorithms such as linear search and binary search.

• Matrices: Arrays are used to represent matrices in mathematical computations


such as matrix multiplication, linear algebra, and image processing.

• 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.

• Graphs: Arrays can be used to represent graphs in computer science. Each


element in the array represents a node in the graph, and the relationships
between the nodes are represented by the values stored in the array.

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

Unformatted input and output :-


gets() and puts():
if we want to read or display the set of strings (sentence or words with space) we make use of gets()
and puts() function for single display at once
22. 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”);
gets(str);
printf(“The entered string is\n”);
puts(str);
}
Array of Strings/Multi-dimensional Strings :-
The two-dimensional array of strings is an array of one-dimensional character array which consist
of strings as its individual elements.
Syntax:
char string_name[size1][size2];
where,
char is a datatype of strings
string_name is a valid identifier which is the name of the string variable
size1 indicates the number of strings in the array
size 2 indicates the maximum length of each string.
Static Initialization of strings:-
char str1[3][10]={“Thomas”,“Bob ”,“Alice”};
Dynamic Initialization of Array of strings:-
23. C program for reading and displaying Array of strings */
#include<stdio.h>
void main()
{
char str[50][50];
int n,i;
printf(“Enter the number of names\n”);
scanf(“%d”,&n);
printf(“Enter %d names\n”,n);
for(i=0;i<n;i++)
{
scanf(“%s”,str[i]
}
printf(“Entered names are \n”);
for(i=0;i<n;i++)
{
printf(“%s\n”,str[i]
}
}

String Manipulating Functions:- C supports different string handling functions to perform


different operations on the strings. All the string handling functions are stored in the header file
“#include<string.h>”.
Some of the most common used built-in string manipulation functions are
• strlen() : Returns the number of character in the given string
• strcmp() : Compares two string for their similarity
• strcpy() : Copies source string into destination string variable
• strcat() : Concatenates (joins) two string into single string
• strrev() : Reverses a given string
• strupr() : Converts characters to upper case
• strlwr() : Converts characters to lower case
String Length :- The function strlen() is used to find the length of the string in terms of number of
characters in it.
SYNTAX: strlen(string_data);

24. C program to find length of the string using strlen() function */


#include<stdio.h>
#include<string.h>
void main()
{
char str1[50]; int len;
printf("Enter a string\n");
scanf("%s",str1); len=strlen(str1);
printf("Length of the String=%d\n",len);
}
***** OUTPUT *****
Enter a string mangalore
Length of the String=9
String Compare:- The function strcmp() is used to compare the string data every character of one
string is compared with the corresponding position character of second string.
SYNTAX : strcmp(str1,str2)
• The function returns 0 if there is complete match (str1==str2)
• Returns positive value if str1>str2
• Returns negative value if str1<str2

25. C program to compare two strings using strcmp( ) function */


#include<stdio.h>
#include<string.h>
void main()
{
char str1[20],str2[20]; int k;
printf("Enter string 1\n");
scanf("%s",str1);
printf("Enter string 2\n");
scanf("%s",str2);
k=strcmp(str1,str2);
if(k==0)
printf("Strings are same\n");
else
}
printf("Strings are different\n");
***** OUTPUT *****
Enter string 1 mite
Enter string 2 mite
Strings are same

26. C program to compare two strings without using strcmp( ) function */


#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void main()
{
char str1[20],str2[20];
int len1,len2,i;
printf("Enter string 1\n");
scanf("%s",str1);
printf("Enter string 2\n");
scanf("%s",str2);
len1=strlen(str1);
len2=strlen(str2);
if(len1!=len2)
printf("Strings are different\n");
else
{
for(i=0;str1[i]!='\0';i++)
{
if(str1[i]!=str2[i])
{
printf("Strings are different\n");
exit(0);
}
}
printf("Strings are same\n");
}}

String Copy:- The function strcpy() copies the content from one string to another string

SYNTAX : strcpy(str2,str1);

27. C program to copy the string using strcpy function */


#include<stdio.h>
#include<string.h>
void main()
{
char str1[30],str2[30];
printf("Enter string1\n");
scanf("%s",str1);
strcpy(str2,str1);
printf("The copied string is = %s\n",str2);
}
***** OUTPUT *****
Enter string1
mite mangalore
The copied string is = mite
String n Copy :-The strncpy() funtion copies the n characters of one string to another string.
SYNTAX : strncpy(dest_string,source_string,n);
Where n is an integer value which specifies the number of characters to be copied

28. C program to illustrate strncpy( ) function */


#include<stdio.h>
#include<string.h>
void main()
{
char str1[30],str2[30];
printf("Enter String1\n");
gets(str1);
printf("String 1= %s\n",str1);
strncpy(str2,str1,10);
printf("String 2= %s\n",str2);
}
***** OUTPUT *****
Enter String1 MANGALORE_INSTITUTE_OF_TECHNOLOGY
String 1= MANGALORE_INSTITUTE_OF_TECHNOLOGY
String 2= MANGALORE_

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 concatenated string is=HarryPotter

String Reverse:- The function strrev() is used to reverse the string .

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);

printf("The Reversed string =%s\n",str1);

***** OUTPUT *****

Enter String1 wingardiamleviosa

The Reversed string =asoivelmaidragniw

31. C program to check if the given string is a Palindrome or not a Palindrome */

#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';

printf("The original String =%s\n",str1);

printf("The reversed String= %s\n",str2);

x=strcmp(str1,str2);

if(x==0)

printf("%s is a palindrome\n",str1);

else

printf("%s is not a palindrome\n",str1);

***** OUTPUT ***** malayalam

The original String =malayalam

The reversed String= malayalam

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];

printf("Enter the string in lower case letters\n");

scanf("%s",str1);

printf("The string in Upper case letter is= %s\n", strupr(str1));

printf("Enter the string in Upper case letters\n");


scanf("%s",str2);
printf("The string in Lower case letter is= %s\n", strlwr(str2));

***** OUTPUT *****

Enter the string in lower case letters dumbledore

The string in Upper case letter is= DUMBLEDORE Enter the string in Upper case letters

HAGRID

The string in Lower case letter is= 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;

printf("\n Enter a sentence\n");

gets(str1);

printf("The entered sentence is\n");

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;

printf("\n The total number of vowels =%d\n",vc);

printf("\n The frequency of vowel a is =%d\n",ac);

printf("\n The frequency of vowel e is =%d\n",ec);

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.

Elements of User Defined Function


The Three Elements of User Defined function structure consists of :
1. Function Definition
2. Function Declaration
3. Function call
1. Function Definition:
➢ A program Module written to achieve a specific task is called as function definition.
➢ Each function definition consists of two parts:
i. Function header
ii. Function body
General syntax of function definition

Function Definition Syntax Function Definition Example

Datatype functionname(parameters) void add()


{ {
declaration part; int sum,a,b;
executable part; return printf(“enter a and b\n”);
statement; scanf(“%d%d”,&a,&b); sum=a+b;
} printf(“sum is %d”,sum);
}
i. Function header
Syntax
datatype functionname(parameters)
➢ It consists of three parts
a) Datatype:
✓ The data type can be int,float,char,double,void.
✓ This is the data type of the value that the function is expected to return to
calling function.
b) functionname:
✓ The name of the function.
✓ It should be a valid identifier.
c) parameters
✓ The parameters are list of variables enclosed within parenthesis.
✓ The list of variables should be separated by comma.

Ex: void add( int a, int b)


➢ In the above example the return type of the function is void
➢ the name of the function is add and
➢ The parameters are 'a' and 'b' of type integer.
ii. Function body
➢ The function body consists of the set of instructions enclosed between { and } .
➢ The function body consists of following three elements:
a) declaration part: variables used in function body.
b) executable part: set of Statements or instructions to do specific activity.
c) return : It is a keyword,it is used to return control back to calling function.
If a function is not returning value then statement is:
return;
If a function is returning value then statement is:
return value;

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.

Function Declaration Syntax


datatypefunctionname(type p1,type p2,………type pn);
Example
int add(int a, int b);
void add(int a, int b);

Note: The function declaration should end with a 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
}

Formal Parameters and Actual Parameters


• Formal Parameters:
➢ The variables defined in the function header of function definition are called
formal parameters.
➢ All the variables should be separately declared and each declaration must be
separated by commas.
➢ The formal parameters receive the data from actual parameters.
• Actual Parameters:
➢ The variables that are used when a function is invoked)in function call) are called
actual parameters.
➢ Using actual parameters, the data can be transferred from calling function. to
the called function.
➢ The corresponding formal parameters in the function definition receive them.
➢ The actual parameters and formal parameters must match in number and type of
data.

Actual Parameters Formal Parameters

Actual parameters are also called as Formal parameters are also


argument list. called as dummy parameters.
Ex: add(m,n) Ex:int add(int a, int b)
The variables used in function call are called The variables defined in function
as actual parameters header are called formal
parameters
Actual parameters are used in calling Formal parameters are used in
function when a function is called or the function header of a called
invoked function.
Ex: add(m,n) Example:
Here, m and n are called actual parameters int add(int a, int b)
{ ………..
}
Here, a and b are called formal
parameters.
Actual parameters sends data to the formal Formal parameters receive data
parameters from the actual parameters.
Example:

• Differences between Actual and Formal Parameters

4.2 Categories of the functions

1. Function with no parameters and no return values


2. Function with no parameters and return values.
3. Function with parameters and no return values
4. Function with parameters and return values
1. Function with no parameters and no return values

1. Function with no parameters and no return values


(void function without parameter)
Calling function Called function

/*program to find sum of two numbers using


function*/
#include<stdio.h> void void add ( )
add( ); {
void main() int sum;
{ printf(“enter a and b values\n”);
add( ); scanf(“%d%d”,&a,&b); sum=a+b;
} printf(“\n The sum is %d”, sum); return;
}

✓ In this category no data is transferred from calling function to called function,


hence called function cannot receive any values.
✓ In the above example,no arguments are passed to user defined function add( ).
✓ Hence no parameter are defined in function header.
✓ When the control is transferred from calling function to called function a ,and b
values are read,they are added,the result is printed on monitor.
✓ When return statement is executed ,control is transferred from called function/add
to calling function/main.
2. Function with parameters and no return values
(void function with parameter)
Calling function Called function

/*program to find sum of two numbers using


function*/
#include<stdio.h> void
add(int m, int n); void
main() void add(int a, int b)
{ {
int m,n; int sum; sum
printf(“enter values for m and n:”); = a+b;
scanf(“%d %d”,&m,&n); printf(“sum is:%d”,sum);
add(m,n); return;
} }

✓ 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

/*program to find sum of two numbers using


function*/
#include<stdio.h> int int add( ) /* function header */

add();
{
void main()
{ int a,b,sum;

int result; printf(“enter values for a and b:”);

result=add( ); scanf(“%d %d”,&a,&b); sum=

printf(“sum is:%d”,result); a+b;

} 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

/*program to find sum of two numbers using


function*/
#include<stdio.h> int
add();
int add(int a, int b) /* function header */
void main()
{
{
int result,m,n; int sum; sum=
printf(“enter values for m and n:”); a+b; return
scanf(“%d %d”,&m,&n); sum;
result=add(m,n); }
printf(“sum is:%d”,result);
}

✓ 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>

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

void swap(int a, int b)


{
int temp;
temp=a;
a=b;
b=temp;
}

➢ 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);
}

void swap(int*a, int*b)


{
int temp;
temp=*a;
*a=*b;
*b=temp;

}
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.

Differences between Call by Value and Call by reference

Call by Value Call by Address


When a function is called the values of When a function is called the addresses of
variables are passed variables are passed
The type of formal parameters should The type of formal parameters should be
be same as type of actual parameters same as type of actual parameters, but they
have to be declared as pointers.
Formal parameters contains the Formal parameters contain the addresses of
values of actual parameters actual parameters.

Scope and Life time of a variable


Scope of a variable is defined as the region or boundary of the program in which the
variable is visible. There are two types
(i) Global Scope
(ii) Local Scope
i. Global Scope:
➢ The variables that are defined outside a block have global scope.
➢ That is any variable defined in global area of a program is visible from its
definition until the end of the program.
➢ For Example, the variables declared before all the functions are visible
everywhere in the program and they have global scope.
ii. Local Scope
a. The variables that are defined inside a block have local scope.
b. They exist only from thepoint of their declaration until the end of the block.
c. They are not visible outside the block.
❖ Life Span of a variable
➢ The life span of a variable is defined as the period during which a variable is
active during execution of a program.
For Example
❖ The life span of a global variable is the life span of the program.
❖ The life span of local variables is the life span of the function, they are created.
Storage Classes
➢ There are following storage classes which can be used in a C Program:
i. Global variables
ii. Local variables
iii. Static variables
iv. Register variables
i. Global variables:
➢ These are the variables which are defined before all functions in global area of
the program.
➢ Memory is allocated only once to these variables and initialized to zero.
➢ These variables can be accessed by any function and are alive and active
throughout the program.
➢ Memory is deallocated when program execution is over.
e.g
#include<stdio.h>
int x;
main()
{
x=10;
printf(“%d”,x);
printf(“x=%d”,fun1());
printf(“x=%d”,fun2());
printf(“x=%d”,fun3());
}
ii. Local variables(automatic variables)

➢ These are the variables which are defined within a functions.


➢ These variables are also called as automatic variables.
➢ The scope of these variables are limited only to the function in which they are
declared and cannot be accessed outside the function.

EX:
#include<stdio.h>
main()
{
int
m=1000;
func2();
} printf(“%d\n”,m);
func1()
{

int m=10;
} printf(“%d\n”,m);

iii. Static variables


➢ The variables that are declared using the keyword static are called
static variables.

➢ 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

➢ Any variables declared with the qualifier register is called a register


variable.
➢ This declaration instructs the compiler that the variable under use is to be
stored in one of the registers but not in main memory.
➢ Register access is much faster compared to memory access. Ex:
register int a;

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

You might also like