Why is the last part of my sequential search algorithm not functioning correctly?

I built my sequential search program and everything checks out ok, but at the last part where its supposed to catch a non existing value and output a message "Value not found" pops up even after the correct message stating that the value is located at the specified location in the array. Basically weather the value is there or not the NOT FOUND message still pops up. what am I do wrong in my code.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
using namespace std;

int sSearch(int A[], int N, int V)
{
	for(int i=1;i<=N; i=i+1)
	{
		if (V==A[i]){
			cout<<"Data found at position:  "<<i<<endl;
		return i;
		}
	}
}

int main(){
	int A[50];
		int N, i, V;
			cout<<"Please enter the size of Array "<<endl;
				cin>>N;
					cout<<"Please enter each numerical value "<<endl;
						for(i=1;i<=N;i++)
							{
							cin>>A[i];
							}
						cout<<"Please enter the digit you are searching for "<<endl;
					cin>>V;
				cout<<endl;
			sSearch(A, N, V);
		if (A[i]!=V){
	cout<<"Value Not Found "<<endl;
	}
system ("PAUSE");
return 0;
}



can anybody give me a clue here???





Is there some reason you're indenting your code in such a retarded manner?

sSearch doesn't return a value if it doesn't find the value it's looking for. It must. Although, since you're ignoring the value sSearch is supposed to return altogether, one wonders why it returns a value at all.
That is the best indentation I've ever seen.
Try
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

int sSearch(int A[], int N, int V)
{
	for(int i=1;i<=N; i=i+1)
	{
		if (V==A[i]){
			cout<<"Data found at position:  "<<i<<endl;
		return i;
		}
	}
		cout << "No match found" << endl;
                return 0;
}

int main(){
	int A[50];
		int N, i, V;
			cout<<"Please enter the size of Array "<<endl;
				cin>>N;
					cout<<"Please enter each numerical value "<<endl;
						for(i=1;i<=N;i++)
							{
							cin>>A[i];
							}
						cout<<"Please enter the digit you are searching for "<<endl;
					cin>>V;
				cout<<endl;
			sSearch(A, N, V);
system ("PAUSE");
return 0;
}


Also consider using dynamic memory for your array, just in case somebody decides to create an array larger than 50 elements. Dynamic Memory: http://www.cplusplus.com/doc/tutorial/dynamic/

For example, instead of using int A[50], You could assign dynamic memory to the array:
1
2
3
4
5
6
7
8
9
10

int main() 
{
int size = 0;
cout << "Please enter the size of the array: ";
cin >> size;
int* A;
A= new (nothrow) int[size];
}
Last edited on
Thank you fellas I finally figured it out by setting i=sSearch. I didn't realize the indentation was such an issue, but thanks.
Topic archived. No new replies allowed.