Get the digits of an int without using arrays
I want to get the digits of a number the user entered without using arrays.
Is it possible?
Thank you very much.
Related Article: Enormous Input using arrays
is a C discussion thread by illuminatus89 that has 2 replies and was last updated 1 year ago.
skiabox
Junior Poster in Training
60 posts since Jun 2007
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0
//Program to get the digits of a number
#include <stdio.h>
int main (int argc, const char * argv[]) {
// insert code here...
int number, right_digit;
int digit[100];
int x = 0;
printf("Enter your number.\n");
scanf("%i", &number);
do {
right_digit = number % 10;
//printf("%i", right_digit);
digit[x] = right_digit;
x = x + 1;
number = number / 10;
} while (number != 0);
printf("\n");
for (int counter = x; counter >= 0; counter--) {
switch (digit[counter]) {
case 1:
printf("one ");
break;
case 2:
printf("two ");
break;
case 3:
printf("three ");
break;
case 4:
printf("four ");
break;
case 5:
printf("five ");
break;
case 6:
printf("six ");
break;
case 7:
printf("seven ");
break;
case 8:
printf("eight ");
break;
case 9:
printf("nine ");
break;
case 0:
printf("zero ");
break;
default:
break;
}
}
return 0;
}
This code seems to work for an int with 9 or less digits.
For some reason I get awkward results when I enter 10 digits or more.
Any ideas?
skiabox
Junior Poster in Training
60 posts since Jun 2007
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0
I think that the problem is the maximum number of the number variable that is declared as an int.
skiabox
Junior Poster in Training
60 posts since Jun 2007
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0
Change number to long and see what happens
WaltP
Posting Sage w/ dash of thyme
11,404 posts since May 2006
Reputation Points: 3,421
Solved Threads: 1,055
Skill Endorsements: 37