Amazon Interview Question

Using only putchar how would you print out the ascii values for each digit in an integer. For example if the integer was 123, then you would want to print the ascii values for 1, 2, and 3.

Interview Answers

Anonymous

Sep 16, 2011

void printASCII(int src) if (src > 9) { printASCII(src/10); } putchar('0' + (src % 10)); }

3

Anonymous

Nov 3, 2011

void print_ascii(int n) { while(n) { int k = (n%10)+'0'; n/=10; putchar(k); printf("\n"); } }

1

Anonymous

Sep 1, 2011

I used a recursive method involving modulus and division by 10. Not hard, just stressful writing it on paper in an interview.

1

Anonymous

Sep 3, 2011

Ah...the above code would just print the numbers itself not ascii values Could be fixed by adding ascii value of 0 char ie. putchar(*input + '0'); input++;

1

Anonymous

Sep 3, 2011

void printAscii( char *input) { while(input) { putchar(*input++); } } This should work as well....printing each char as an integer would give its ascii value