Exercise: Linear Search

In this exercise you will need to write a function which checks if a given element can be found in an array. The function should return an index of the first occurrence of this element in the array if it's found, or -1 if it's not there.

int linear_search(int element, int *arr, int size) {
	...
}

The size of the array will not be greater than 10000.

To test your code, I'll format the standard input in a special way. The first number in the input is size, number of elements in the array. The following size numbers are array elements. Starting from the next number, and till the end of the input, there will be numbers to look for; for each of them, print its index in the array, or -1, one per line.

For example, for the following input:

5
1 5 4 4 3
1
2
3
4
5
10

defines an array of 5 elements 1 5 4 4 3 and then 6 numbers to look for: 1, 2, 3, 4, 5, 10. Your code should produce the following output:

0
-1
4
2
1
-1

which means that:

I'll let you write the code!

#include <stdio.h>

int linear_search(int element, int *arr, int size) {
	/* your code here */

	return -1;
}

int main() {
	int arr[10000];
	int size;

	/* your code here: read size */
	/* your code here: read array elements */

	/* your code here: read the remaining numbers
     and call linear_search for each one, and print the result
   */

	return 0;
}

I'll give you some hints.

First, scanf("%d", &size) will read a number into a memory location where the variable size is allocated. Since after this line we know exactly how many array elements to read, we can use a for loop to read them all:

int i;

for (i = 0; i < size; ++i) {
	scanf("%d", &arr[i]);
}

After we got all the elements, we should keep reading until the end of your input. To do that, we look at the return value of scanf. If it was successful, it returns the how many values it has read, so we can just call it while it returns 1 (one number read):

int element;

while (scanf("%d", &element) == 1) {
	/* call linear_search function */
}

Did all the tests pass?