Wednesday, February 1, 2017

2D Array Search

C program to search an element in to 2D Array.




#include<stdio.h>
int main()
{
int A[3][3], i, j, number, flag=0;
for (i=0; i<3; i++) {
for(j=0; j<3; j++)
{
printf("Enter your element[%d][%d]:",i,j);
scanf("%d", &A[i][j]);
}
}
printf("Your array is:\n");
for (i=0; i<3; i++) {
for(j=0; j<3; j++)
printf("%d ",A[i][j]);
printf("\n");
}
printf("Enter the value to be search:");
scanf("%d",&number);

for (i=0; i<3; i++) {
for(j=0; j<3; j++)
{
if(A[i][j]==number)
{
flag=1;
break;//exit(0);
}
}
}
if (flag==1)
printf("%d: Present in Array.",number);
else
printf("%d: Not in Array", number);
return 0;
}

Output - 1

Enter your element[0][0]:1
Enter your element[0][1]:2
Enter your element[0][2]:3
Enter your element[1][0]:4
Enter your element[1][1]:5
Enter your element[1][2]:6
Enter your element[2][0]:7
Enter your element[2][1]:8
Enter your element[2][2]:9
Your array is:
1 2 3
4 5 6
7 8 9
Enter the value to be search:5
5: Present in Array.

Output - 2

Enter your element[0][0]:1
Enter your element[0][1]:2
Enter your element[0][2]:3
Enter your element[1][0]:4
Enter your element[1][1]:5
Enter your element[1][2]:6
Enter your element[2][0]:7
Enter your element[2][1]:8
Enter your element[2][2]:9
Your array is:
1 2 3
4 5 6
7 8 9
Enter the value to be search:0
0: Not in Array


* * * * *

No comments:

Post a Comment