Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting integer to integer array in c [duplicate]

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};
like image 465
erickimme Avatar asked Apr 09 '26 22:04

erickimme


1 Answers

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
like image 168
bejado Avatar answered Apr 12 '26 11:04

bejado



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!