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.
#include <iostream>
usingnamespace 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;
}
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.
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];
}