I have posted the code in open form, so I would have hoped you figure out and rectify the mistake yourself. (But the mistake was not a didactic means, it did happen involuntarily.)
Yes, there was a mistake – the while-clause does not terminate at changing the variable "theCheck" but when it closes (with the "}" bracket) so "theIndex" was reduced by 1 after meeting the condition.
So the options are
• starting ""theIndex" at 256 and subtracting at the beginning instead of the end of the while-clause or
• adding 1 to "theIndex" when using it in "applyThreshold"