I do not find any flaw as such in the code you provide. But the fact is Newton method does not always gives the output for following reasons:
I. If the function does not does not intersect the x-axis (i.e. no root) at all. Few trivial example is f(x)=5 and f(x)=sin(x)+10. Another slightly non trivial example being f(x)=x/sqrt(abs(x)). Verify that if the function falls under this category.
II. If the function does have root, try to increase 'N' and the tolerance (tol) and check. And also you may try to put the initial guess 'x0' more closer to the actual root and check.
If the above does not answer your question, then provide the function and other parameters for which it's not working.