-7
#include <iostream>

float x[10], k;
int n, i;

cout<<"N= "; cin>>n;

for (i=0; i<n; i++){
    cout<<"x["<<i<<"]= ";
    cin>>x[i];
}

cout<<"Array's elements: ";
for (i=0; i<n; i++)
    cout<<x[i]<<", ";

cout<<endl<<"K= "; cin>>k;
for(i=0; i<n; i++)
    if(x[i]!=k){
        cout<<endl<<"K doesn't exist in array.";
        cout<<endl<<"K= "; cin>>k;
    }

I am trying to find if an element exists in array, if it doesn't exist I want to re-type the element and to repeat the whole array and check it. Mine doesn't get it from the start (i=0).

Nick28
  • 3
  • 1
  • 1
  • 3
  • 6
    That's pretty obvious. You can't declare that an element is not in the array after checking just the first one. – LogicStuff Aug 14 '17 at 17:41
  • 3
    [`std::find`](http://en.cppreference.com/w/cpp/algorithm/find) – Cory Kramer Aug 14 '17 at 17:42
  • What you wrote is a check that *all* of the elements are the one you’re looking for. If you don’t want to use standard algorithms (you really should use standard algorithms), you need to use a flag to see if any of them matched. – Daniel H Aug 14 '17 at 17:48
  • To avoid the flag break from the loop when the match is found, so i is still at the index position. Then test if i < n. if you know something about your data (like expecting many consecutive duplicates) then it may be worthwhile to adjust the iteration (like starting at the end). But use some library, and think about hashing. – smoe Aug 14 '17 at 17:56
  • What do you think about this writing method with arrays learnd at school? Is it good or I need to improve it or I can simplify it? – Nick28 Aug 14 '17 at 18:25

3 Answers3

3

There is the perfect function for that in the standard library - std::any_of - if all you want to know is if something exists.

If you also need access to the found element, then there is std::find or std::find_if.

If you want to know how many times something exists, the standard library has you covered with std::count and std::count_if.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
  • 1
    I do some exercises for school and we haven't learned this kind of exercises yet. But I will try anyway. Thanks! – Nick28 Aug 14 '17 at 18:18
2

There is a standard function called std::find in the header <algorithm>:

#include <iostream>
#include <algorithm>

int main() {
    int myarray[6]{10, 4, 14, 84, 1, 3};

    if (std::find(std::begin(myarray), std::end(myarray), 1) != std::end(myarray))
        std::cout << "It exists";
    else
        std::cout << "It does not exist";
    return 0;
}

Ideone

Post Self
  • 1,471
  • 2
  • 14
  • 34
-2

Try to make a new variable called cnt and use it like this -

for(i=0; i<n; i++)
    if(x[i]==k){
        ++cnt;

    }
if (cnt==0)
    cout << "k has not occured";
else
    cout<<"k has occured"<<cnt<<"times";
Kadhem
  • 11
  • 5