How do I store different digits of an integer in any array
like 1234 to {1,2,3,4}
It can be done using char str[]="1234"; printf("%c",str[0];
but how to do it without using string and in integer itself
CodePudding user response:
Here's a snippet that creates an array of digits and prints them out:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
// Print digits 1 by 1
void numToDigits (int number, int base) {
int i;
int n_digits = (int)ceil(log(number 1) / log(base));
printf("%d digits\n", n_digits);
int * digits = calloc(n_digits, sizeof(int));
for (i=0; i<n_digits; i) {
digits[i] = number % base;
number /= base;
}
// digits[0] is the 1's place, so print them starting from the largest index
for (i=n_digits-1; i>=0; --i) {
printf("%d", digits[i]);
}
printf("\n");
free(digits);
}
You'll likely want to modify this, but I think it exposes all the important ideas. Don't forget to add -lm
when you compile to include math libraries needed for log
and ceil
. Also note that the printing code isn't made to work with bases larger than 10.
CodePudding user response:
Here's one method, more or less:
get the
log10()
of the integer to determine its 'size'take the
floor()
of that to get exponent (number of digits - 1)then calculate the highest divider with
(int)pow(10, exponent)
finally have a
for
-loop:int value = 1234; // Your value to split up in digits. for (int d = divider; divider > 0; divider /= 10) { int digit = value / d; value = value / 10; // Store digit in array }
I leave the details for you to fill in.
Carson had a similar idea which nicely avoids the use of pow()
CodePudding user response:
I was writing my response when the first answer showed up. This will work just fine. The loop in the middle basically isolates each digit by removing all the ones in front of it and then dividing it down to the ones place before adding it to the array.
CodePudding user response:
If your compiler supports variable length arrays then you can use the approach shown in the demonstration program below
#include <stdio.h>
enum { Base = 10 };
size_t size( unsigned int x )
{
size_t n = 0;
do { n; } while ( x /= Base );
return n;
}
int main( void )
{
unsigned int x = 0;
printf( "Enter a non-negative number: " );
scanf( "%u", &x );
size_t n = size( x );
unsigned int digits[n];
for ( size_t i = n; i != 0; x /= Base )
{
digits[--i] = x % Base;
}
for ( size_t i = 0; i < n; i )
{
printf( "%u", digits[i] );
}
putchar( '\n' );
}
The program output might look like
Enter a non-negative number: 123456789
123456789
If the compiler does not support variable length arrays then you will need to allocate the array dynamically as for example
unsigned int *digits = malloc( n * sizeof( unsigned int ) );