Wednesday, 7 August 2013

Index value won't change

Index value won't change

I'm trying to implement a linear search function to search for a
particular number in which the user "inputs" however, say for example the
user wants to search for the number 3 in the given array. The function
should return an index value of 2. But my code returns 6 no matter what
input I enter. I suspect there is something wrong in my main function
(maybe while I am using a for loop, the value of i gets fixed to 6?). Any
ideas?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define numberOfElements 6
#define NOT_FOUND -1
int linearSearch (int *myArray, int key, int i);
int main (int argc, char *argv[]){
int i, key, myArray[] = {1, 2, 3, 4, 5, 6};
printf("Input: ");
for (i = 0; i < numberOfElements; i++){
printf("%d ", myArray[i]);
}
printf("\n");
printf("Please enter a number you wish to search for: ");
scanf("%d", &key);
linearSearch (myArray, key, i);
printf("The number %d is at index %d\n", key, i);
return 0;
}
int linearSearch (int *myArray, int key, int i) {
for (i = 0; i < numberOfElements; i++){
printf("Checking index %d\n", i);
if (myArray[i] == key){
printf("%d\n", i);
return i;
break;
}
printf("It's certainly not here!\n");
}
return NOT_FOUND;
}

No comments:

Post a Comment