I was wondering if anyone can tell me the error with my code. I’m trying to make an algorithm that searches through elements in an array, and returns ‘true’ if the element is ‘less than i’ and ‘greater than u’. I can’t quite understand why this doesn’t seem to work. It sometimes returns true but appears to ignore the first element of the array, others not so much.
Additionally to this, I want to experiment with a ‘divide and conquer’ version of this, now I understand some of the theory behind this. The use of a ‘pivot’ point and dividing the array into two smaller problems but have no idea how to implement it, if anyone can elaborate on either of these issues I’d be most grateful. thanks.
#include <iostream>
using namespace std;
bool ArrayCheck(int length) {
int A[] = { 5, 10, 20, 25, 50 };
int i = 40; //less Than
int u = 15; //Greater Than
for (int Count = 0; Count < length; Count++) { //Counter
if (A[Count] <= i && A[Count] >= u) { //Checker
return true;
break;
} else {
return false;
}
}
}
int main() {
cout << ArrayCheck(5);
}
Is the else supposed to be there? It seems like the
else { return false }line should just be removed and you could addreturn falseafter the entire loop…Should be something like: