Hey guys, love the forum so far and learning a lot. I'm taking some new computer science classes trying to get a handle on programming in C++ with Visual Basic 2010 using Windows on my laptop.
As the title says one of the functions in my assignment is to search for a value within an array. I've done some research but the answers seem to be case to case basic but I did determine some things.
I know I need to use a for loop and I think the one I am using is on the right track. I know that I need to test if each value in my array is the same as the one I want to look for and if it is not then to continue on to the next value and so on and so forth. Here is my code so far.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
elseif (xin == 6) {
for (int x=0; x<HEIGHT; x++)
for (int y=0; y<WIDTH; y++) {
cout << "Enter the number you would like to search for: " << endl;
cin >> SearchVal;
for (int z=0; z<4; z++)
for (z=0; z<5; z++)
{
if (z==SearchVal)
cout << "Value exists" << endl;
else (z!=SearchVal)
cout << "Value does not exist in array" << endl;
}
}
}
So now that you see what I am trying to do how to I set up my for loop so that 'i' will apply the parameters to my matrix and check each value there. My idea was using those two for loops would ensure that 'i' would not exceed the column width or row width of my array.
Thanks in advance for the help and I hope my question is clear. I will post back and respond to all questions, comments, and solutions!
C++ guarantees that the 2D array is contiguous in memory (i.e. all next to each other), so you can just start with the first element and go through all the rest in sequence:
1 2 3 4 5 6 7 8 9 10 11
int* currentElement = &(givenArray[0][0]); // Create pointer to first element
cin >> SearchVal;
for (int i=0; i<HEIGHT*WIDTH; i++)
{
if (*currentElement == SearchVal)
{ cout << "Value exists" << endl;
break;
}
currentElement++;
}
you can even use the STL std::find: find(array[0], array[n-1]+m, x)//array is your 2D array, n is the first dimension, m is the second and x is your value
That was an incredibly thorough and great response!
I was wondering how I could simplify this to using just one for loop. I appreciate the help Moschops! You showed me a little bit about pointers and everything I needed for this problem. I appreciate it man!
@viliml
What do you refer to that type of function as? The thing is my professor did not ever explain how to use something like that (actually he cancelled the last day of class to skip traffic to catch a flight and did not explain much) and I am not sure if he would accept our program to have something included in that.
HOWEVER, with that being said I have noticed that the STL std has many functions similar to what you just pointed out, such as sort, that I could be using. What would I refer to these as so I can look for a tutorial about implementing them?