Run Output
Give the number to find :9
Found at row =3 col = 1
-OR-
Give the number to find :15
Not Found
int arr[3][4]={{1 ,2 ,3 ,4 }, {5 ,6 ,7 ,8 },{9 ,10,11,12}};
This is pre-initialised integer array of 3 row and 4 row size. Total 12 members are filled there.
int n,row=0,col=0,found=0;
n will contain the user’s search input, row and col will contain the position where searched item is found. found=0 means that we begin from initial value of 0 for found variable to assume that it is not found.
cout<<“Give the number to find :”; cin>>n;
Here we collect the search term from the user.
for(int i=0;i<3;++i) //This is external loop that runs for the row count.
{
if(found==1) break;
This we do first so that if some time later in loop found is set to 1 we can immediately exit the loop. This is done because in the problem we have assumed that only one instance of any item would be found.
for(int j=0;j<4;++j) //This is internal loop that works on column count.
{
if(n==arr[i][j]) //Here we check the search term with a match with the array member
{
row=i+1; col=j+1;
If search term is found than position of given index has to be increased by one. If item is found at 0,0 index then the position will be 1,1.
found=1;
The found variable is set to 1 so that in next entry of outer loop the loop can break immediately.
}
}
}
if(found) cout<<“Found at row =”<<row<<” col = “<<col<<endl;
The row and col position values are printed when the search term is found.
else cout<<“Not Found”<<endl;
This is the not found case.
Notes
- Please note that index of 2D arrays begins from 0,0 while the position begins from 1,1 . For this reason careful understanding of question is required whether the index has to be printed or the row, col position has to be printed.
Common Errors
- If a student forgets to initialise found with 0 erroneous results will come when the member is not found, it may still report as found.