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.
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.
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.
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.
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; }
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;
}
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++;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With