# Linear Sequence Search

This is a discussion on Linear Sequence Search within the C Programming forums, part of the General Programming Boards category; Hi everybody, I just registered to the forum, I will be asking questions so much during those months, hope I ...

1. ## Linear Sequence Search

Hi everybody, I just registered to the forum, I will be asking questions so much during those months, hope I won't be too annoying

The first thing I want to ask to you is this:
My professor just gave me this simple program that finds a key in an array..
Code:
```
#include <stdio.h>
#define V 5

int seqS(int v[], int l, int r, int k);

main()
{
int i, k, a[V];

for (i=0; i<V; i++)
{
printf("Input a[%d]:", i);
scanf("%d", &a[i]);
}
printf("Input key:  ");
scanf("%d", &k);
system("pause");
}

int seqS(int v[], int l, int r, int k)
{
int i=l;

while (i<r && k!=v[i])
i++;
if (i==r)
return -1;
return i;
}```
I tried to change the while part with a for loop but it doesn't seem to work..
Here's my changes

Code:
```int seqS(int v[], int l, int r, int k)
{
int i;

for (i=l; i<r; i++)
if (v[i]==k)
return (i);
else return (-1);
}
```

it just keeps giving me -1 in return...
what did I do wrong?

Thanks

2. Your for loop will only execute at l, that is one time, since the else statement is attached to your if() statement...

Effectively... "Is this it? No. Oh Darn. Send -1"

If you construct your loop like this...
Code:
```int seqs(int v[], int l, int r, int k)
{ int i;

for (i = l; i < r; i++)
if (v[i] == k)
return i;

return -1; }```
... Now each element of the array from l to r-1 will be tested before it returns -1.

One might quip that you need to be careful or ELSE.

3. Oh my god thank you!
i know it was just a stupid problem... The way I did it, the program would have just searched for k at the first position! In fact if i had put k== v[0] it would have worked!
Thanks again

4. No worries... it's always the silly stuff that trips me up too...

5. Using braces ALL the time forces you to think a bit more about what is really going on.

As would a consistent and meaningful approach to indentation.

I hope you can see how your code would fail just from looking at it, with these ideas in place.
Code:
```int seqS(int v[], int l, int r, int k)
{
int i;

for (i=l; i<r; i++) {
if (v[i]==k) {
return (i);
} else {
return (-1);
}
}
}```