2

For example take 123 and put it into an array where that is a[3] = {1, 2, 3}?

Without converting it to a string and iterating over it.

4 Answers 4

5

You can get the decimal digits of a number by using integer division and modulo.

 //Pseudo code
 int[MAX_SIZE] result;
 int index = 0;
 while (workingNumber > 0)
 { 
     digit = workingNumber % 10;
     result[index] = digit;
     workingNumber = workingNumber / 10; //Must be integer division
     index++;
 } 
Sign up to request clarification or add additional context in comments.

1 Comment

Note that for the given example the digits will be {3, 2, 1} in the array, i.e. you need to reverse it to get what OP asks for.
3
#include <math.h>

...

int number = 5841;
int size = log10(number) + 1;
int arr[size];
int i = size;
while(i >= 0)
{
    arr[--i] = number % 10;
    number /= 10;
}

Comments

1

First, keep in mind that in C the only real difference between "array of char" and "string" is to be a string, you put a NUL-terminator at the end of the array of char.

Assuming you wanted (for example) to create an array of int (or long, or something else other than char), you'd typically take the remainder when dividing by 10 and convert it to a digit by adding '0'. Then divide the number by 10 and repeat until it's reduced to zero. That creates the numbers from least to most significant, so you normally deposit them at the end of the array and work backward toward the beginning.

Comments

1
#include <stdio.h>
#include <math.h>

#define LEN 3

int main(int argc,char* argv[])
{
  int i = 123;
  int a[LEN];
  int digit;
  int idx = log10(i);

  do {
    digit = i % 10;
    i /= 10;
    a[idx--] = digit;
  } while (i != 0);

  printf("a: { %d, %d, %d }\n", a[0], a[1], a[2]);

  return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.