5

I am writing a code to display the digits of any positive integer in C language. For example, integer 345 would displayed as three four five.

The code I wrote works fine for integers with all digits greater than 0. But certain integers like 10, 304, 0 etc don't get displayed correctly. Usage of recursion and array is not allowed for the sake of challenge. Only looping and if constructs are allowed. Any suggestions?

#include<stdio.h>
int main(void)
{
    int num, num_copy, accum = 1;

    printf("Enter an integer ");
    scanf("%i",&num);

    num_copy = num;

    while (num > 0){

    while (num > 9){
        num = num / 10;
        accum *= 10;
        }
        switch (num){

        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;
        }
        num_copy = num_copy - (num*accum);
        num = num_copy;
        accum = 1;
    }

    return 0;
}
user1825355
  • 191
  • 1
  • 3
  • 11
  • Why parenthesis around case labels? Why not around other constants? `accum *= (10);` or `return (0);` – pmg Nov 15 '12 at 15:38
  • Try stepping through the code line by line. You will notice several problems when you do that. – Raymond Chen Nov 15 '12 at 16:42

5 Answers5

2

If you write a recursive function, it would help you avoid the loops that you use to print in the reverse order:

#include<stdio.h>

void print_num(int num)
{
if(num == 0) return;
print_num(num/10);

        switch (num%10){

        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;
        }
}


int main(void)
{
    int num, num_copy, accum = 1;

    printf("Enter an integer ");
    scanf("%i",&num);
    print_num(num);

    return 0;
}

Non-recursive solution which uses an array to store the numbers:

void print_num(int num)
{
int i=0,j;
int arr[256];

while(num)
{
arr[i++]=num%10;
num/=10;
}

for(j=i-1; j>=0;j--)
{
        switch (arr[j]){

        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;
        }
}
P.P
  • 117,907
  • 20
  • 175
  • 238
  • your solution is perfect. I forgot to mention that this problem was meant to be solved without recursion. Only looping and if constructs were allowed. Any more ideas? – user1825355 Nov 15 '12 at 15:42
  • I see. You can simply store the numbers in an array and print then? – P.P Nov 15 '12 at 15:47
  • sorry once again, no arrays too ! – user1825355 Nov 15 '12 at 15:49
  • Well, you keep adding constraints :) I just updated the array solution. Let me think the non-array, non-recursive one :) – P.P Nov 15 '12 at 15:52
  • Basically you need to reverse the number in one way or another. Recursive/array solution uses additional memory proportional to the length of the number whereas the alternative would incur the same amount of time complexity. You can convert the number into a string and reverse it then print it in the same way. Basically, you can't use a loop solution which can't handle numbers that end with zeroes like 10, 200, etc. – P.P Nov 15 '12 at 16:03
  • @user1825355 - `you can't use a loop solution which can't handle numbers that end with zeroes` - meaning you just need special handling for numbers like 100 (ie. see my example with the `backupzeros` variable) – Mike Nov 15 '12 at 17:03
2

Ohh! This sounds like fun! No arrays and no recursion right?

So since we can't use recursion we need to build the number backwards:

#include<stdio.h>
int main(void)
{
    int num, backwards = 0, digit, backupzeros = 0;

    printf("Enter an integer ");
    scanf("%i",&num);            // get the number

    while(num > 0){
        digit = num % 10;    // pry off the last digit
        num /= 10;           // take off the digit

        if((backwards == 0) && (digit == 0))    // If it's a number that ends in 0
            backupzeros++;                   // save it, we'll use that later

        backwards = (backwards * 10) + digit; // glue it on backwards
    }

    // Now we have the number reversed. Next we need to print the digits

    while (backwards > 0){
        digit = backwards % 10;
        backwards /= 10;

        switch (digit){

        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;
        default:
                printf("zero ");
                break;
        }
    }

    while(backupzeros > 0) {
        printf("zero ");
        backupzeros--;
    }

    return 0;
}
Mike
  • 47,263
  • 29
  • 113
  • 177
  • I probably shouldn't have written the whole thing since this sounds like a homework assignment... but I could use a break today. :) – Mike Nov 15 '12 at 16:29
  • this is no way a homework assignment. I am way past that age. I am an airline pilot, learning how to program a computer. thanks for the time you spent replying to my question.. – user1825355 Nov 16 '12 at 01:50
  • @user1825355 - I am of the opinion that your never too old to go back to school. (ironically, I'm a software enginer but I'm going back to get a pilots license) and I'm happy to help out, as you can see even with the restrictions of no recursion and arrays, its possible to solve the problem, you'll find most problems have many different solutions. – Mike Nov 16 '12 at 04:52
  • awesome solution ! I am amazed with the power of % operator and 'apparently flawed' division in integer arithmetic! good to know your interest in flying. Do you already have some flying experience? – user1825355 Nov 17 '12 at 16:23
  • @user1825355 - Yeah, `%` and `/` is a great combination, you can do a lot with it. And yes, I do, I've flown a 172 Cessna Skyhawk a handful of times now, including landing and taking off, I find it very enjoyable (no doubt as its for personal rather than professional reasons. ;)) – Mike Nov 19 '12 at 12:14
  • I cherished flying cessna 152 during my training days. flying is only enjoyable in small aircrafts. Commercial flying is monotonous and uncreative. – user1825355 Nov 19 '12 at 16:30
1

This is was an Univ exercise, many many years ago !!!

integers from 1 to 999

#define MAX_BUF 100

int main(){

    int num, i=0, j, digit;
    char *buf[MAX_BUF];

    printf("Integer: ");
    scanf("%d",&num);

    while(num){
        digit = num %10;
        num = num /10;

        switch(digit){
            case 0: buf[i++] = "zero"; break;
            case 1: buf[i++] = "one"; break;
            case 2: buf[i++] = "two"; break;
            case 3: buf[i++] = "three"; break;
            case 4: buf[i++] = "four"; break;
            case 5: buf[i++] = "five"; break;
            case 6: buf[i++] = "six"; break;
            case 7: buf[i++] = "seven"; break;
            case 8: buf[i++] = "eight"; break;
            case 9: buf[i++] = "nine"; break;
        }
    }

    for(j = i-1; j >= 0; j--){
        printf("%s-", buf[j]);
    }

    return 0;
}
b3h3m0th
  • 1,330
  • 1
  • 11
  • 22
0

"(..)But certain integers like 10, 304, 0",

What all of these numbers have in common? "Zero" is the answer.

You must put in your switch the condition to handle the zero also.

You can do something like this:

#include<stdio.h>
int main(void)
{
    int num, num_copy, accum = 1;

    printf("Enter an integer ");
    scanf("%i",&num);

    char str[15];
   sprintf(str, "%d", num);


    for(num = 0; str[i] != '\O'; num++)
    {
      switch (num){

        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;
        }
    }

    return 0;
}

You can use sprintf() to convert the integer into a char []. Then you just need to iterate over that array.

dreamcrash
  • 47,137
  • 25
  • 94
  • 117
0

Untested...

char *digitNames[10] = {
    "zero",
    "one",
    ...   // Too lazy to fill in the rest..
    "nine"
}

void displayNumber(uint32_t number) {
    int totalDigits = 0;
    int scale = 10;
    uint32_t divisor = 1000000000;
    uint32_t digit;

    do {
        scale--;
        digit = number / divisor;
        number -= digit * divisor;
        divisor /= 10;
        if(scale == 0) {
            fputs(stdout, digitNames[digit]);
        } else if( (digit != 0) || (totalDigits != 0) )
            printf("%s ", digitNames[digit]);
            totalDigits++;
        }
    } while(scale != 0);
}
Brendan
  • 35,656
  • 2
  • 39
  • 66