c - Index value won't change -
i'm trying implement linear search function search particular number in user "inputs" however, example user wants search number 3 in given array. function should return index value of 2. code returns 6 no matter input enter. suspect there wrong in main function (maybe while using loop, value of gets fixed 6?). 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: "); (i = 0; < numberofelements; i++){ printf("%d ", myarray[i]); } printf("\n"); printf("please enter number wish search for: "); scanf("%d", &key); linearsearch (myarray, key, i); printf("the number %d @ index %d\n", key, i); return 0; } int linearsearch (int *myarray, int key, int i) { (i = 0; < numberofelements; i++){ printf("checking index %d\n", i); if (myarray[i] == key){ printf("%d\n", i); return i; break; } printf("it's not here!\n"); } return not_found; }
you ignore return value linearsearch
function. hence don't print answer.
note should not pass i
function instead declare within loop:
for (int i=0; i<... etc
Comments
Post a Comment