0

I'm doing pset3 and I seem to have a functioning linear search. But I can't find my "needle" if it's in a higher array position than 331, which is where 127 is (I've copied the output of "generate" to a txt file). The program works just fine up to position 330 in the array. Can anyone help me?This is what my search code looks like

Also, can someone please explain why I need to use (n) in the array brackets? Thanks in advance!

1 Answer 1

2

In your for loop you have

for (n = 0; n < values[n]; n++)

The values[n] has the value of the nth element in the values array. So on the first iteration you have n == 0 and you check, is 0 < values[0]? then on the second iteration you check, is 1 < values[1]? When what you want to check is if n is smaller than the length of the array, not a value in the array. Also n is the length of the array, and its value is passed in your function. You shouldn't assign to it 0. So your for loop should look like that:

for (int i = 0; i < n; i++)

And the answer to your final question, you mustn't use n in brackets in your for loop. You use the values[i] notation to get the ith element in your array.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .