# Storing an int as individual digits in an array

• 12-17-2007
Wiretron
Storing an int as individual digits in an array
I have an int i, say 6473, and I want to store each digit separately in an array, like so:

array[0] = 6;
array[1] = 4;
array[2] = 7;
araay[3] = 3;

How can I do this?

thx
• 12-17-2007
laserlight
What have you tried?
• 12-17-2007
Elysia
What is the problem, I would ask? You specifically mention an array - is the problem that you do not know how to create or declare an array?
• 12-17-2007
Wiretron
I know how to declare an array, I just don't know how to split an int into an array.
• 12-17-2007
Elysia
Ah, now I understand. So basically, each digit into its own array. For that I would ask if you actually answer laserlight's question.
I could also provide some insight - how would you do it mathematically in the real world?
• 12-17-2007
Wiretron
Quote:

Originally Posted by Elysia
Ah, now I understand. So basically, each digit into its own array. For that I would ask if you actually answer laserlight's question.
I could also provide some insight - how would you do it mathematically in the real world?

No that's not what I meant.

Think of it this way, ignore the whole array part, the question really is:

How would I access each individual digit of the number: 45656

i.e. what would I have to do to access the 4?
• 12-17-2007
laserlight
Quote:

How would I access each individual digit of the number
Suppose you divide the number by 10. What is the remainder?
• 12-17-2007
Wiretron
Quote:

Originally Posted by laserlight
Suppose you divide the number by 10. What is the remainder?

Ah k, in the end I've just decided to convert to a string
• 12-17-2007
Elysia
Admittedly, it's possible without a string, but a bit tricky. Here's an example!
Code:

```        const int mynum = 12345;         int num1 = ( mynum - (mynum / 10 * 10) ) / 1;         int num2 = ( mynum - (mynum / 100 * 100) ) / 10;         int num3 = ( mynum - (mynum / 1000 * 1000) ) / 100;         int num4 = ( mynum - (mynum / 10000 * 10000) ) / 1000;         int num5 = ( mynum - (mynum / 100000 * 100000) ) / 10000;```
num1 = 5, num2 = 4, num3 = 3, num4 = 2, num5 = 1
• 12-17-2007
cpjust
Might I suggest sprintf()...
Code:

```char str[12]; int num = 12345; sprintf( str, "%d", num );```
• 12-17-2007
matsp
Actually, it's not very difficult to do your own as long as you store the string from the back. But obviously much less code to use sprintf() [at least of code "that you write yourself"].

--
Mats
• 12-17-2007
Elysia
Arguably, the easiest way is to convert to string first, then take each element and covert back to integer again. Although the OP did specify that it was converted to a string in the end.