I solved this problem by recursively adding the digits of the number until a single digit number is obtained and the program worked fine. I searched the web and found a very small solution for it which i was unable to understand: