0

I'm working on a sample from my textbook regarding 2 dimensional arrays. It has the following example that allows the user to input a value, and then it searches the array and returns the location of the element that contains the value, or alerts them if the value doesn't exist.

What I'm wondering, is what if multiple elements contain the user's value? In the code, I added some loops to initialize the 2d array, and multiple elements contain the same value. How would I set up the search that it would return multiple elements as containing the search value?

#include <stdio.h>

int main() {

int iTwoD[3][3];
int iFoundAt[2] = {0};
int x, y;
int iFound, iValue = 0;


//initialize the 2-d array
for ( x = 0; x<=2; x++) {

  for (y=0;y<=2;y++)
    iTwoD[x][y] = (x+y);
} //end outer loop

//print the 2-d array
for (x=0; x<=2; x++){

  for (y=0;y<=2;y++)
    printf("iTwoD[%d][%d] = %d\n", x, y, iTwoD[x][y]);

}//end outer loop

//Get the user's value to search for
printf("\nEnter your search value: ");
scanf("%d", &iValue);

//Search the 2-d array for user's value
for (x = 0; x<=2; x++) {
  for (y = 0; y<=2; y++) {
    if ( iTwoD[x][y] == iValue) {
      iFound = 1;
      iFoundAt[0] = x;
      iFoundAt[1] = y;
      break;
    } //end if
  } //end inner loop
} //end outer loop

if (iFound ==1)
  printf("\nFound value in iTwoD[%d][%d]\n", iFoundAt[0], iFoundAt[1]);
else
  printf("\nValue not found\n");

return 0;
} //end main
1
  • Use an array to store the results. Commented Mar 4, 2013 at 23:47

2 Answers 2

1
if ( iTwoD[x][y] == iValue)
{
   arrayOfResults[i][0]=resultx;
   arrayOfResults[i++][1]=resulty;
}
Sign up to request clarification or add additional context in comments.

1 Comment

it doesn't stop the loop after finding a single result, but keeps going until the end of 2d array and stores all the correct results in an array
1

You'll need to increase your iFoundAt to be able to hold more than a single tuple of (x,y). In addition, you'll need to remove the break from the search since you need to search the entire matrix despite the found value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.