Tuesday, October 4, 2011

Data Structure Lab Programs - Write a program to search an element in a two dimensional array using linear search

Practical # 1

 

/* Write a program to search an element in a two dimensional array using linear search .*/

 

#include<stdio.h>

#include<conio.h>

void main()

{

int arr[10][10],n,m,i,j,search;

clrscr();

printf("\n\n\t\tLinear Search");

printf("\n\n\nNo. of rows of an array:");

scanf("%d",&n);

printf("\nNo. of columns of an array:");

scanf("%d",&m);

printf("\nEnter the elements of an array:\n");

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

{

for(j=0;j<m;j++)

scanf("%d",&arr[i][j]);

}

printf("\nThe matrix entered is\n");

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

{

for(j=0;j<m;j++)

{

printf("%d ",arr[i][j]);

}

printf("\n");

}

printf("\nEnter the element to be searched:");

scanf("%d",&search);

int pos=0,pos1=0;

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

{

for(j=0;j<m;j++)

{

if(arr[i][j]==search)

{

pos=i+1;

pos1=j+1;

}

}

}

if(pos>0 || pos1>0)

{

printf("\n\nThe position of the searched element is[%d][%d]",pos,pos1);

printf("\nwhere %d is row",pos);

printf("\nwhere %d is column",pos1);

}

else

printf("\n\nThe element does not exist in the matrix");

getch();

}

 

 

 

 

Output :-

 

Linear Search

No. of rows of an array:2

No. of columns of an array:2

 

Enter the elements of an array:

1 2

3 4

 

The matrix entered is

1 2

3 4

 

Enter the element to be searched:3

 

 

The position of the searched element is[2][1]

where 2 is row

where 1 is column

 

 

 

No comments :

Post a Comment