linear search

hi
I have a problem in this code
 ``123456789101112131415161718`` ``````void l_search() { int item,i; int arr[] = {2,3,4,5,6,2,3,44,5,3,5,3,4,7,8,99,6,5,7,56,5,66,44,34,23,11,32,54,664,432,111}; cout << "Enter the item you want to find: "; cin >> item; for(i=0;i<31;i++) { if(item==arr[i]) cout << "Item is found at location " << i+1 << endl; } if(i>=31) cout << "Not exist!" << endl; } ``````

well
I want to print "Item is found at location ....."and end the function when I find any element of the array.
and if the item is not exist I want to print "Not exist!" and end the function.
but in the first case it prints "Item is found at location ....." and prints "Not exist!" too !!!!
can any one helps my? :(
The value of `i` inside the loop goes from 0 to 30. When it reaches 31, the `for` loop terminates.

Next i, which has just reached the value of 31 is tested like this: `if(i>=31)`. This condition is true, so the "not exist" message is output.

One solution is to add a `break` statement like this:
 ``12345678`` `````` for (i=0; i<31; i++) { if (item==arr[i]) { cout << "Item is found at location " << i+1 << endl; break; } }``````

The only problem with this is the case when you want to search for a value like 44, which occurs at more than one position. This code will now find only the first occurrence.

If you need to find all occurrences of a value, you could use a boolean variable. Set it to false before entering the loop. When the value is found, instead of the break, set the bool value to true. After the loop is completed, test the bool value to see whether or not the item was found.
Last edited on
I would write the following way

 ``1234567891011`` `````` i = 0; while ( i < sizeof( arr ) / sizeof( *arr ) && arr[i] != item ) i++; if( i != sizeof( arr ) / sizeof( *arr ) ) { cout << "Item is found at location " << i+1 << endl; } else { cout << "Not exist!" << endl; }``````
Last edited on