Thread: Number 0 getting lost in the program

  1. #1
    Registered User
    Join Date
    Apr 2020
    Posts
    3

    Number 0 getting lost in the program

    Hello everyone

    Newbie here, I am self-learning C using Programming in C by Steve kochan, I am currently doing Chapter 6 exercise 6 for those that have worked with this book before,

    Program simply takes a number from the user, and writes it out in words, (932 = nine three two), my logic when I wrote it was to have a loop reversed the number and then have another loop stracking the last digit using modulus and the print it out with a switch statement, so far so good.

    But when I go and input number 0, because of the modulus operation it gets lost of course and it ends up not printing.

    Here is my code

    Code:
     // program that takes an integer and prints out the word
    
    #include <stdio.h>
    
    int main(void)
    {
          int userNumber, tempNumber, rightDigit, newNumber = 0;
    
          printf("Please enter any nonnegstive 3 digit number: ");
          scanf_s("%i", &userNumber);     // ask for users input
      
          if (userNumber < 0 || userNumber > 999)
         {
               printf("Number is out of the range!\n");    
         }                            // checks for numbers outside of range 
     
         do
         {                // loop to reverse the number, ex 932 to 239
               rightDigit = userNumber % 10;
               tempNumber = rightDigit;
                  
               if (userNumber > 99 && userNumber < 1000)
              {
              tempNumber *= 100;
              newNumber += tempNumber;
              }
              else if (userNumber > 9 && userNumber < 100)
             {
              tempNumber *= 10;
              newNumber += tempNumber;
              }
              else if (userNumber >= 0 && userNumber < 10)
             {
              newNumber += tempNumber;
             }
            userNumber /= 10;
     } while (userNumber != 0);
    
     do
     {            // loop to extrac the last digit and assigned the word in   english for that number
           rightDigit = newNumber % 10;
    
           switch (rightDigit)
           {
            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;
      }
    
      newNumber /= 10;
    
     } while (newNumber != 0);
    
     printf("\n");
    
     return 0;
    }
    I know I can look up this problem online and find its solution but I am trying to avoid doing that until I finish it to compare my code and someone else,

    Any help will be appreciated

    Thanks

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    38,112
    I didn't see anything obvious, and it seems to work.
    Code:
    $ gcc -Wall foo.c
    $ ./a.out 
    Please enter any nonnegstive 3 digit number: 0
    Zero
    $ ./a.out 
    Please enter any nonnegstive 3 digit number: 123
    One Two Three 
    $ ./a.out 
    Please enter any nonnegstive 3 digit number: 42
    Four Two
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    27,839
    You seem to have made some effort to do so, but one simple thing that will help to make your code readable is to indent your code consistently. For example:
    Code:
    // program that takes an integer and prints out the word
    
    #include <stdio.h>
    
    int main(void)
    {
        int userNumber, tempNumber, rightDigit, newNumber = 0;
    
        // ask for users input
        printf("Please enter any nonnegstive 3 digit number: ");
        scanf_s("%i", &userNumber);
    
        // checks for numbers outside of range
        if (userNumber < 0 || userNumber > 999)
        {
            printf("Number is out of the range!\n");
        }
    
        // loop to reverse the number, ex 932 to 239
        do
        {
            rightDigit = userNumber % 10;
            tempNumber = rightDigit;
    
            if (userNumber > 99 && userNumber < 1000)
            {
                tempNumber *= 100;
                newNumber += tempNumber;
            }
            else if (userNumber > 9 && userNumber < 100)
            {
                tempNumber *= 10;
                newNumber += tempNumber;
            }
            else if (userNumber >= 0 && userNumber < 10)
            {
                newNumber += tempNumber;
            }
            userNumber /= 10;
        } while (userNumber != 0);
    
        // loop to extract the last digit and assigned the word in english for that number
        do
        {
            rightDigit = newNumber % 10;
    
            switch (rightDigit)
            {
            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;
            }
    
            newNumber /= 10;
    
        } while (newNumber != 0);
    
        printf("\n");
    
        return 0;
    }
    Quote Originally Posted by Dizzy2k11
    Program simply takes a number from the user, and writes it out in words, (932 = nine three two), my logic when I wrote it was to have a loop reversed the number and then have another loop stracking the last digit using modulus and the print it out with a switch statement, so far so good.

    But when I go and input number 0, because of the modulus operation it gets lost of course and it ends up not printing.
    It looks like you aren't strictly dealing with 3 digit numbers, so my suggestion is to read the number as a string. This makes the conversion really simple as you won't have to deal with reversing the number.

    If instead you know that you are strictly dealing with 3 digit mumbers, e.g., you will not have a two digit number like 20 that could get confused with 200 as both would be reversed to result in the number 2, a possible solution while keeping to your current approach is to change the way the printing loop terminates: instead of looping while newNumber != 0, change it with the help of a counter to always loop 3 times. This way, for 200, you will reverse it to get 2, and then you will print Two, update newNumber to be 0, and from then on you will print Zero and Zero, which is exactly what you want.

    If you must read the input as an integer, and you must deal with numbers that could be 1 or 2 digits, then your approach of reversing the number will only work if you also keep track of the number of digits of the number (i.e., count the digits while reversing), and then change the printing loop to loop that many times.

    By the way, your loop to reverse the number is more complex that it needs to be: you don't have to check the range of userNumber with that if-else chain as you just need to multiply the current reversed number by 10 before adding the extracted digit. It is at this point that you can increment the digit counter if you're going with the last approach.

    Quote Originally Posted by Salem
    I didn't see anything obvious, and it seems to work.
    Try 200
    Last edited by laserlight; 04-22-2020 at 11:14 PM.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    38,112
    Try 200
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  5. #5
    Registered User
    Join Date
    Apr 2020
    Posts
    3
    Quote Originally Posted by laserlight View Post
    You seem to have made some effort to do so, but one simple thing that will help to make your code readable is to indent your code consistently. For example:
    note taken, my apologies, I tried to indented as much as possible , it is my first post here and couldn't figure out a way besides tapping the space bottom 1000 times.

    Quote Originally Posted by laserlight View Post
    It looks like you aren't strictly dealing with 3 digit numbers, so my suggestion is to read the number as a string. This makes the conversion really simple as you won't have to deal with reversing the number.
    Have not gotten that far in the book yet, no idea how to use strings yet to be honest

    Quote Originally Posted by laserlight View Post
    If instead you know that you are strictly dealing with 3 digit mumbers, e.g., you will not have a two digit number like 20 that could get confused with 200 as both would be reversed to result in the number 2, a possible solution while keeping to your current approach is to change the way the printing loop terminates: instead of looping while newNumber != 0, change it with the help of a counter to always loop 3 times. This way, for 200, you will reverse it to get 2, and then you will print Two, update newNumber to be 0, and from then on you will print Zero and Zero, which is exactly what you want

    If you must read the input as an integer, and you must deal with numbers that could be 1 or 2 digits, then your approach of reversing the number will only work if you also keep track of the number of digits of the number (i.e., count the digits while reversing), and then change the printing loop to loop that many times.
    The counter worked out perfectly, increase the counter by 1 on the first loop and decrease on the second until it hit 0, and it printing in numbers like 200,

    Quote Originally Posted by laserlight View Post
    By the way, your loop to reverse the number is more complex that it needs to be: you don't have to check the range of userNumber with that if-else chain as you just need to multiply the current reversed number by 10 before adding the extracted digit. It is at this point that you can increment the digit counter if you're going with the last approach.
    Not quite understanding you here,

    But if I multiply tempNumber by 10 before I go in the chain and then add the do the newNumber += tempNumber , I just adds the numbers up which it gives me a wrong reversed number,

    Thanks much

  6. #6
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    27,839
    You need to multiply newNumber by 10 before you add tempNumber.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  7. #7
    null pointer Structure's Avatar
    Join Date
    May 2019
    Posts
    266

    Cool Numbers ...

    Program simply takes a number from the user, and writes it out in words, (932 = nine three two),
    Code:
    #include <stdio.h>
    #include <string.h>
    
    
    #define stringLength 32
    #define out(i) printf(i)
    #define figure(x) showNumber( (int)x )
    
    
    void translate( char number ) {
        switch ( number ) {
            case '0': out("zero"); break;
            case '1': out("one"); break;
            case '2': out("two"); break;
            case '3': out("three"); break;
            case '4': out("four"); break;
            case '5': out("five"); break;
            case '6': out("six"); break;
            case '7': out("seven"); break;
            case '8': out("eight"); break;
            case '9': out("nine"); break;
            default:
                printf("\n");
            break;
        }
    }
    
    
    void showNumber( int numb ) {
        char stringValue[ stringLength ];
        sprintf( stringValue, "%d", numb );
        for (int i = 0; i < strlen(stringValue); i++) {
            translate( stringValue[ i ] );
            if (i == (strlen(stringValue) - 1) ) break;
            printf( "%c", stringLength );
        }
    }
    
    
    int main() {
        figure( 53445 );
        return 0;
    }
    "without goto we would be wtf'd"

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    27,839
    This is pretty bad:
    Code:
    printf( "%c", stringLength );
    It looks like you want to print a space as in Dizzy2k11's code, so print a space, don't print stringLength that just happens to have the ASCII value for a space. Besides, it is also a poor name because it is the array size, not the string length.

    Also, the out and figure macros seem pretty useless, and the figure macro is technically incorrect: it should be (int)(x) instead because macro expansion could mean that x becomes an expression for which the cast might be grouped with only part of the expression.

    I'd just compute strlen(stringValue) once, then reuse it in both the loop condition and in the check for the last valid element.

    Instead of a switch, it may be easier to have a static array of strings, then you just check that the value is a digit, upon which you can subtract '0' and use it as an index into the array.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  9. #9
    Registered User
    Join Date
    Dec 2017
    Posts
    950
    Recursion is useful for reversing the number.
    Code:
    #include <stdio.h>
     
    void print(unsigned long n) {
        static const char *ones[] = {
            "zero", "one", "two",   "three", "four",
            "five", "six", "seven", "eight", "nine" };
        if (n > 9) p(n / 10);
        printf("%s ", ones[n % 10]);
    }
     
    int main() {
        print(1234567890);
        putchar('\n');
        return 0;
    }
    Last edited by john.c; 04-24-2020 at 05:41 PM.
    If you want the truth to stand clear before you, never be for or against. - Sent-ts'an

  10. #10
    Registered User
    Join Date
    Apr 2020
    Posts
    3
    Thanks everyone for all the help, was able to get the code to work properly, I really appreciate it.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Lost and need help with C Program
    By sstudent911 in forum C Programming
    Replies: 7
    Last Post: 03-15-2013, 09:50 AM
  2. Replies: 2
    Last Post: 12-19-2005, 06:57 PM
  3. Files Program... really lost
    By thynksheraze in forum C++ Programming
    Replies: 2
    Last Post: 09-25-2003, 07:30 PM
  4. Lost with this program....
    By Jamina in forum C++ Programming
    Replies: 3
    Last Post: 08-09-2003, 09:21 AM
  5. Lost ID number
    By ripper079 in forum C++ Programming
    Replies: 13
    Last Post: 10-04-2002, 12:51 PM

Tags for this Thread