Help correct the error in the function.

It should give the value 1 of the bool variable if the number is at least once in the array, and 0 if the number is not included.

bool vhod(int a, int b[], int n) { for (int i = 0; i < n; i++) { if (a == b[i]) return true; break; if (a != b[i] && i == n-1 && vhod == 0) return false; } } 

With input data:

 a = 7 n = 3 b[] = {0, 5, 14} Vhod = 1 

What is wrong?

  • five
    Your break is executed unconditionally at the first iteration. Because of this, the return value is undefined, since there is no corresponding return . The fact that the function returned the unit to you is pure coincidence. - окт
  • @Arhad, how to fix it then? - Alone_Fox
  • @Alone_Fox remove it and all the condition "if (a! = B [i] ...", and after the cycle - return false add - Vladimir Martyanov
  • @Alone_Fox, bool vhod(int a, int b[], int n) { bool found = false; for (size_t i = 0; i < n && !found; i++) found = (a == b[i]); return found;} bool vhod(int a, int b[], int n) { bool found = false; for (size_t i = 0; i < n && !found; i++) found = (a == b[i]); return found;} bool vhod(int a, int b[], int n) { bool found = false; for (size_t i = 0; i < n && !found; i++) found = (a == b[i]); return found;} - ߊߚߤߘ

1 answer 1

If you have already left the loop, then nothing has been found. What else do you want to check? ...

 bool vhod(int a, int b[], int n) { for (int i = 0; i < n; i++) if (a == b[i]) return true; return false; }