Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert an integer number into an array

Tags:

arrays

c

I am trying to convert an integer number in C into an array containing each of that number's digits

i.e. if I have

int number = 5400

how can I get to

int numberArray[4]

where

numberArray[0] = 0;
numberArray[1] = 0;
numberArray[2] = 4;
numberArray[3] = 5;

Any suggestions gratefully received.

like image 444
droseman Avatar asked Feb 05 '09 12:02

droseman


People also ask

How do you convert an integer to a char array?

Approach: The basic approach to do this, is to recursively find all the digits of N, and insert it into the required character array. Count total digits in the number. Declare a char array of size digits in the number. Separating integer into digits and accommodate it to a character array.

Is it possible to convert an integer to a string?

The reason I ask is because I know it is possible to convert an integer into a String so I was hoping there was other shortcuts for me to learn as well. An example of what I am trying to do is taking int 10382 and turning it into int array {1, 0, 3, 8, 2} Any help or guidance will be much appreciated, thank you very much.

How to convert a number to an array in JavaScript?

In this article, we will use two different methods to convert the given number into an array. Method 1: Using Array.from () Method: The JavaScript Array from () method returns an Array object from any object with a length property or an iterable object. Store a number in a variable.

How many decimal digits are there in an array of numbers?

There are 7 members of the array, but only 6 decimal digits in the number. int array [6]; int number = 123456; for (int i = 5; i >= 0; i--) { array [i] = number % 10; number /= 10; }


2 Answers

Try this,

void initialise_array(int *a, int size, int num) {
    for (int i = 0; i < size; ++i, num /= 10)
        a[(size - 1) - i] = num % 10;
}
like image 182
Dylan R Coss Avatar answered Oct 12 '22 00:10

Dylan R Coss


Hint: Take a look at this earlier question "Sum of digits in C#". It explains how to extract the digits in the number using several methods, some relevant in C.

From Greg Hewgill's answer:

/* count number of digits */
int c = 0; /* digit position */
int n = number;

while (n != 0)
{
    n /= 10;
    c++;
}

int numberArray[c];

c = 0;    
n = number;

/* extract each digit */
while (n != 0)
{
    numberArray[c] = n % 10;
    n /= 10;
    c++;
}
like image 30
Zach Scrivena Avatar answered Oct 12 '22 02:10

Zach Scrivena