1. Linear Search

Hi, I'm pretty new to C programming. Writing a program to search through an array and print the number and its position. The program compiles and runs and if the value entered is not present in the array i get the correct result , however if the value is present it prints 0 in position 0. If possible could someone please help me find the error.
Code:
```#include<stdio.h>
#include<stdlib.h>
#define SIZE 100

int Search(const int set[] , int key, int size);/*Linear search function*/

int main(void)
{
int num[SIZE];/*Array of numbers*/
int i;/*counter*/
int search;/*Integer to be searched for*/
int element;/*Stores value returned from function*/

for ( i = 0; i < SIZE ; i++)
{
num[i] = i * 2;/*Get values for array*/
}

printf("Enter a number to search for\n");
scanf("%d" , &search);

element = Search(num , search , SIZE);/*Call function*/

if (element != -1 )
{
printf("The number %d was found at position %d" , num[element] , element);
}
else
{
}
system("PAUSE");
return 0;
}

int Search(const int set[] , int key , int size)
{
int n = 0;

while( (set[n] != key) && (n < size))
{
if( set[n] == key)
{
return n;
}
else
{
n++;
}
}

if (n >= size)
{
return -1;
}

}```

2. I'm thinkin' you're over thinkin'...

Try this...
Code:
```int Search(const int set[] , int key , int size)
{
int n = 0;
while(n < size)
{
if( set[n] == key)
return n;
n++;
}
return -1;
}```
You correctly return the index when you find it...
The only other thing to do is increment the counter... which won't happen if it returns.
If the loop ends, it didn't find it so return -1

You had the right idea... you just went a little overboard.

3. Since you apparently already know how to use for loops, use a for loop instead of a while loop here.

4. Thank you ,its working now. I understand why the extra bits were unnecessary. Learned something today

5. Originally Posted by tsmith94
Thank you ,its working now. I understand why the extra bits were unnecessary. Learned something today
To learn some more... try it Lase's way, with a for loop...

6. Thanks. I was over thinking it , is why i didn't use a for loop. I changed it.