How would you write a linear search using a for loop?

Answered by 2teez 43 in a post from

Hi Estermont ,

What have you tired?

## All 4 Replies

Hi Estermont ,

What have you tired?

Let's say you have an array consisting of ten numbers: [ 1 2 3 4 5 6 7 8 9 10 ]. Now you would like to find number 7. You can start at the beginning, look at each number in the array individually, and then stop when you find a 7.

Something like:

``````for (i = 0; i < sizeOf(array); i++)
{
if (array[i] == 7)
{
found at position i
break out of for loop
}
}``````

or instead of breaking out of the loop ....

``````int indexOfElement;
for (i = 0; i < sizeOf(array); i++)
{
if (array[i] == 7)
{
found at position i
indexOfElement = i;
i = sizeOf(array);
}
}``````

I dunnnno, for readability's sake, I think it makes better sense to break out of the loop than to start introducing a second variable and changing the value of the iterator (i). Obviously the ideal way would be to use a while loop here (while value of array with index ++i is not equal to 7), but the assignment was to use a for loop, so I digress.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.