HW#3 Frequently Asked Questions (FAQ)

  • How do I check whether a given number is "too large" to add a given digit to it?
  • How do I check whether a character is a digit? An uppercase letter?
  • How do I read a character at a time without skipping '\n'?
  • How do I check whether a given number is "too large" to add a given digit to it?
    The largest number that a (so-called "signed") int can hold is represented by a symbolic constant called INT_MAX declared in limits.h. Any statement that tries to put a value larger than INT_MAX into an int is likely to give wildly incorrect results.

    Now, back to the problem at hand. No matter what digit we try to add on to the number, there must be room to "shift" the number over and add a zero on to the end. This can only work if the number is sufficiently smaller than INT_MAX. In particular:

      number * BASE <= INT_MAX
    
    The trouble is that number * BASE may, in fact, be too big to represent. So, we don't want to even try doing that calculation. What can we do then? Just adjust the inequality:
      number * BASE / BASE <= INT_MAX / BASE
      number               <= INT_MAX / BASE
    
    The use of integer division in the final inequality won't be a problem. See if you can understand why.

    Now, we can shift the number over, but then we need to ask whether the digit will fit on to the end of the number. This is even simpler than the last question; we just need to know whether this is true:

      shifted_number + digit_value <= INT_MAX
    
    Again, we don't want to actually perform the calculation on the left. Can you figure out how to avoid it as we did above?

    If both these checks are passed, the number is not too large to fit.

    How do I check whether a character is a digit? An uppercase letter?
    We won't fully answer this question, but here's a hint: you can use inequality operators with characters in reasonable circumstances. So, for example, the following inequalities are all true:
      '3' > '0'
      '2' < '9'
      'C' > 'B'
      '0' == '0'
      'C' != 'c'
      'A' < 'Z'
    
    What about an inequality like 'C' > '3'? You should avoid relying on the truth value of this inequality. This is not because the value is not known or specified by the C language. Instead, it's because it's difficult for readers of your code to understand what you're doing if you rely on such facts.

    How do I read a character at a time without skipping '\n'?
    scanf("%c", &character); will read a single character without skipping anything. scanf does not skip whitespace when reading characters. It will only skip the whitespace if you read a number (int or double) or put in a space in the format string.