The iterations do not converge to an answer. Therefore the do...while loop will not exit when a is negative. You could modify the function by returning 0 for negative inputs.