How do I convert an integer value to integer array format?
For example:
int answer = 140;
and expected value that I wish to get is:
int arr_answer[] = { 1, 4, 0};
If you know the number of digits ahead of time (in this case 3), you can do it like this:
#include <stdio.h>
int main()
{
const int numDigits = 3;
int answer = 140;
int digits[numDigits];
int i = numDigits - 1;
while (answer > 0)
{
int digit = answer % 10;
answer /= 10;
digits[i] = digit;
printf("digits[%d] = %d\n", i, digits[i]);
i--;
}
return 0;
}
Output:
digits[2] = 0
digits[1] = 4
digits[0] = 1
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