for example i got int of 15569542 and i wan to separate them to single digit like
1
5
5
6
9
5
4
2
please help and thank for ur help
for example i got int of 15569542 and i wan to separate them to single digit like
1
5
5
6
9
5
4
2
please help and thank for ur help
1) Compute int%10 (modulo 10). Store the result (last digit) in some array.
2) Divide int by 10.
3) Repeat
int asd=98765, k[5], i;
for(i=0;i<5;i++)
{
k[i]=asd%10;
asd=asd/10;
}
like this correct??
Last edited by lancetky; 04-17-2010 at 11:08 AM.
Well yes, but that assumes that you know how many digits there are in advance. A more general way would be:
I haven't tested this but it's something along these lines.Code:int asd = 98321, k[5], i =0; while(asd > 0){ k[i++] = asd % 10; asd = asd/10; } /* To print the asd digits in the right order you must print k[] in reverse */ int j; for(j = i-1;j >= 0;j--){ printf("%d",k[j]); }
i think i got it. thank for ur help =D
Here's an alternate way ....
Code:#include <stdio.h> #define MAX 999999 #define str(x) # x #define xstr(x) str(x) int main(void) { int d; char array[sizeof xstr(MAX)]; fputs("Enter an integer from 0 to " xstr(MAX) ": ", stdout); fflush(stdout); if (fscanf(stdin, "%d", &d) == 1 && d >= 0 && MAX >= d) { sprintf(array, "%d", d); for (d = 0; array[d] != '\0'; ++d) { printf("%c\n", array[d]); } } else { puts("Try again."); } return 0; }$ gcc -Wall -Wextra alt.c -o alt
[cd@localhost oakland]$ ./alt
Enter an integer from 0 to 999999: 923451
9
2
3
4
5
1
[cd@localhost oakland]$