I want to get the digits of a number the user entered without using arrays.
Is it possible?
Thank you very much.

Is it possible?

Yes, it is possible.
Post some code and mod me up and we'll talk about how you go about doing it.

Edited 6 Years Ago by AuburnMathTutor: n/a

//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?

I think that the problem is the maximum number of the number variable that is declared as an int.

Yeah, 10 digit ints are getting pretty high up there. A 32-bit signed integer can hold a maximum value of 2^31 - 1 = 2147483647. As you can see, this is indeed a 10-digit number. My hypothesis is that if you try to give your program anything bigger than that number, it probably isn't going to behave.

How do you get around that?

Well, you can try bigger integer types. Really, for what you're doing, you probably want to read the data as string data, because then the digits are manifest and the length of the number's decimal representation is no longer a real concern.

Yeah, a higher data type will solve the problem for you...
Anyway you have done a mistake in the code.
Your for loop counter should start from (x-1) and not x, as the value of x will be one more due to the last "x=x+1" statement at the do-while loop.
Check it !!!

This article has been dead for over six months. Start a new discussion instead.