I'm not sure what your programming level is, but this would be much easier to do with a while loop.