i am trying to find any user entered value in a array which the user has previously entered the values of. I made the following for finding which values were entered in array bu
You are solving a finding problem here. You have no any suggestions where the entered value may
probably be, so you should try each one step by step. This is a common problem.
The first way to solve it is to use a loop. It isn't a good way for modern C++. But you should probably
try it for a practice.
bool has(int val, int const* arr, size_t size) {
size_t idx = 0;
// Iterates each element of array and checks
// whether the one is equal to the `val`. In
// case of meeting of `val`, the loop stops.
while (idx < size && arr[idx] != val) ++idx;
return idx != size;
}
The way below is more convinient. Actually, the more general form of has
function is already has in C++ standart library in
header. It is called find
. It do exactly the same, but much better. Actually, there are a lot of functions solving a common problems in
header. You have to use it anywhere you can.
bool has_(int val, int const* arr, size_t size) {
int const* end = arr + size;
// Now `has_` don't iterate each element and
// checks it. It finds the `val` in range
// between the first element of array and
// the last.
return std::find(arr, end, val) != end;
}
I suggest you to read the subsection "Prefer algorithm calls to handwritten loops." in section "STL: Containers" in the book
"C++ Coding Standarts" by Herb Sutter and Andrei Alexandrescu
to gain an intuition about why to use the
header.
Also, you may find the reference to the
header here.
Lets consider your code and discuss why you end up with error. Actually, you just made a typo.
It is the one of the reasons to use the
header instead of handwritten loops like yours.
#include
#include
using namespace std;
void main()
{
int a[10], found;
for (int i = 0; i<10; i++)
{
cout << "enter value : ";
cin >> a[i];
}
cout << "Enter Searching Value :";
cin >> found;
for (int i = 0; i<10; i++)
{
// Look at here: you compare entered value ten times
// with the value after the last element of array.
if (found == a[10])
{
// In case that you found an entered value in array
// you just continue the loop. You should probably
// break it at this point. This may be achieved by
// using the `brake` operator or the `while` loop.
cout << "Value Found";
_getch();
}
else if (found != a[10])
cout << "Value Not Found";
}
_getch();
}