I'm going to assume your question is a homework assignment. That is why I will ignore the requirement of using a while loop, as a for loop or a vectorized solution is a much better idea.
You can find guidelines for posting homework on this forum here. If this is a homework question, this answer should be completely useless and prompt you to put in some effort. If it isn't homework, you now have a much better solution.