Q:

How do I manipulate the digits of a number?

In some kinds of problems I often face this situation where I have a variable where I need to rearrange the digits, e.g., int e = 2385;. Let's suppose I don't know which number is stored there, but still I need to shift 2nd and 4th position. When I know variable's value I can simply do e = 2583, but when I don't know I simply can't solve the problem.
Another situation is when I have two values and want to use them to form another number i.e int a = 2, b = 1;, and I need to order them so that I will get a 21 or a 212. I mean, that's easy to do when I'm outputting data, I can simply do:
printf("%d%d\n",a,b); 
printf("%d%d%d",a,b,a);

Problem is when I have to store this number in another variable. I don't know how to do that.

A:

This can be broken into two tasks: (1) breaking up a number into pieces, and (2) combining pieces into a whole number.

To break up a number into pieces, use the division and modulus operators.
int num = 2385;

int a = num / 1000;       // 2
int b = num / 100 % 10;   // 3
int c = num / 10  % 10;   // 8
int d = num / 1   % 10;   // 5

The trick is to use division to remove the digits to the right, then modulus to keep only the rightmost digit. For example, to calculate the hundreds' place (b) we compute 2385 / 100, which is 23. 23 % 10 is the remainder when you divide 23 by 10. The remainder is 3.
To combine the pieces back into a number, do the opposite with multiplication and addition.
num = a * 1000            //   2000
    + d *  100            // +  500
    + c *   10            // +   80
    + b *    1;           // +    3
                          //   ----
                          //   2583

Notice how I switched d and b to swap those digits.

