Boolean function error

But the problem is that this function is good if I know the number of elements in the array, otherwise it doesn't work!
Last edited on
int length = sizeof(myarray)/4;

Winner(myarray, length);

Is this what you were after?
You need to put the comparison in a loop, so it's something like this.
1
2
3
4
5
int stop = x/2;
for (int i=0; i<stop; ++i) {
    if (br[i] != br[x-i]) return false;
}
return true;

Note that I have intentionally left a bug in here to help you walk through the process of creating the algorithm. The basic idea is plain, but to get it right you need to check against a bunch of possible "off-by-one" errors. Ask yourself these questions:
- What is the right value for "stop"? Consider an odd and an even value of x to determine this (like x=4 and x=5).
- What are the right values to compare? When i=0 it should compare against the last value in the array.
- Does it work in degenerate cases like when x=0, x=1 and x=2?

Note that I store the ending value of a loop in a variable rather than putting the expression in the loop itself. This is because C++ evaluates the expression each time and why make the computer do the division when the answer won't change? If optimization is turned on then the compiler will figure out that it can do this, but personally I like to do it myself.


sizeof(myarray)/4;THere are compilers where size of int is either 8 or 2. And one of them is, sadly, still widely used. Do not hardcode type size.

Also it will not work if array decayed to pointer, for example you passed it from another function, you will not get correct results.

Use C++style safe array size, which fails in compile time if size cannot be reliably determined.

Alternatively, do not use C-style arrays at all, and use C++ container, which knows own size, instead.
dhayden Thank you very much you are such a great guy.

And thanks to the other guys for their help.

#Respect
Topic archived. No new replies allowed.