- #1
Piddler
- 1
- 0
Hi, new to the forum, it is a really spiffy place. I'm not really much of a programmer, but I have an interest in it and kind of like to piddle around with programming. I am learning C and C++ mostly by doing, browsing books, and asking dumb questions of people who know a lot more about it than I do.
So here is a dumb question. I have been playing with arrays and I am trying to learn how to search through arrays. I managed to pull a piece of code from a book I've been reading ( I will show it below), and it works well. I want a search that will tell me if a number is in an array, and if so all of the locations that it can be found at.
Here is the code I found, it is a function and it is in C.
the problem is that only returns the first one that it finds. how do I make it so that it returns all instances of the number matching the key?
Again, I am kind of a novice that just tinkers for fun, so go easy on me. Thanks, I really like your forums!
So here is a dumb question. I have been playing with arrays and I am trying to learn how to search through arrays. I managed to pull a piece of code from a book I've been reading ( I will show it below), and it works well. I want a search that will tell me if a number is in an array, and if so all of the locations that it can be found at.
Here is the code I found, it is a function and it is in C.
Code:
/* compare key to every element of array until the location is found
or until the end of array is reached; return subscript of element
if key or -1 if key is not found */
int linearSearch( const int A[], int key, int size )
{
int n; /* counter */
/* loop through array */
for ( n = 0; n < size; ++n ) {
if ( A[ n ] == key ) {
return n; /* return location of key */
} /* end if */
} /* end for */
return -1; /* key not found */
} /* end function linearSearch */
the problem is that only returns the first one that it finds. how do I make it so that it returns all instances of the number matching the key?
Again, I am kind of a novice that just tinkers for fun, so go easy on me. Thanks, I really like your forums!