Suppose you want to write a program in C++ which will take a positive integer from the user and output its individual digits. For example, if the input provided is 12345 then it will print 1,2,3,4 and 5 separately as integers. In this article we shall look at a few different ways of accomplishing exactly this.

First of all, look at the following program. It is probably the simplest way of separating digits of an integer. It makes use of the fact that when the division operator (/) is used with two integer operands then it gives us only the whole part of the quotient and the remainder operator (%) gives us the remainder when dividend is divided by the divisor. In this particular case, we use 10 with both these operators as divisor. When we use it with the remainder operator we get the last digit of the number entered by the user and when we use it with the division operator then we get the original number without that last digit. In this way, repeating these two steps until the original number becomes zero, we get each individual digit of the original number form right to left i.e. from least significant to most significant digit. Continue reading “C++ Program to Separate Digits of a Positive Integer”