New to using arrays, and C++ all together for that matter but heres my problem.
I've created a program that asks the user to give 20 numbers then to search for a specific number within that array. I have a very good idea as to where i've gone wrong but am clueless on what I need to change it to, heres my code.
#include <iostream>
usingnamespace std;
int main()
{
int key, i, j, array[20];
for(int i=0; i<20; i++)
{
cout << "Enter number: ";
cin >> array[i];
}
cout << "Enter a number to look for in your array" << endl;
cin >> key;
for(int j = 0; j < 20; j++)
{ //I believe I've went wrong here.
if(array[j] == key)
{
cout << "The number " << key << " was found in the array" << endl;
}
else
{
cout << key << " was not found in the array" << endl;
return 0;
}
}
}
the output constantly states that the number wasn't found in the array.
In C++, you normally declare variables where you first need them. Declareing i and j in the first line in your code is redundant. I suggest you use a named constant for the 20 value.
You can also replace your manual search loop with the standard library find function, like this:
#include <iostream>
usingnamespace std;
constint SIZE = 20;
int main()
{
int key, array[SIZE];
for(int i=0; i<SIZE; i++)
{
cout << "Enter number: ";
cin >> array[i];
}
cout << "Enter a number to look for in your array" << endl;
cin >> key;
if(find(array, array+SIZE, key) != array+SIZE)
{
cout << "The number " << key << " was found in the array" << endl;
}
else
{
cout << key << " was not found in the array" << endl;
}
}
You might also replace the array with a vector, like this:
#include <vector>
#include <iostream>
usingnamespace std;
constint SIZE = 20;
int main()
{
int key;
vector<int> vec(SIZE);
for(int i=0; i<SIZE; i++)
{
cout << "Enter number: ";
cin >> vec[i];
}
cout << "Enter a number to look for in your array" << endl;
cin >> key;
if(find(vec.begin(), vec.end(), key) != vec.end())
{
cout << "The number " << key << " was found in the array" << endl;
}
else
{
cout << key << " was not found in the array" << endl;
}
}
Of course, with vector you probably want to let the user decide how many number to put in, and use push_back instead of cin >> vec[i]. If you want to ignore duplicates, you might want set instead of vector...