Hi All,

I have a question that is related to Arduino on the periphery. (C for beginner’s is related, right?)

I have been teaching myself C with the 1st Edition of this book by KN King. https://www.amazon.com/Programming-Approach-K-N-King/dp/0393969452/ref=asap_bc?ie=UTF8

I am currently on chapter 7, and I am really stumped on the question I pasted below.

I found a solution that works (tested the output in Visual Studio) from this discussion topic that took place over 10 years ago: Re: [C] Reading and arithmetic with getchar()

The solution definitely works, but I am unsure what the reasoning is for the line with the statement that goes "digit = ch - ‘0’; " The solver provided some sparse notes. I do understand that you can look at charts converted numbers to ASCII character values, and that 0 is indeed 48 in ASCII.

I am just scratching my head why he’s subtracting ‘0’ from the input variable ch.

Can someone walk me through what’s happening in that While loop?

I pasted the question and solution below. And to preserve formatting, I also attached a word Doc with formatting

Many thanks in advance!!!

Question Text

11). Airline tickets are assigned lengthy identifying numbers, such as 47715497443. To be valid, the last digit of the number must match the remainder when the other digits—as a group—are divided by 7

Example: (4 + 7 + 7 + 1 + 5 + 4 + 9 + 7 + 4 + 4) % 7 = 3 /* modulo, not division */

For example, 4771549744 divided by 7 yields the remainder of 3.

Write a program that checks whether or not an airline ticket number is valid

Hint: Don’t attempt to read the number in a single step.

Instead, use getchar to obtain its digits one by one. Carry out the division one digit at a time, being careful not to include the last digit in division.

Solution from: Re: [C] Reading and arithmetic with getchar()

```
#include <stdio.h>
#include <ctype.h> /* for access to the toupper function */
main()
{
char ch; /*char is the ticket number */
int digit; /*digit represents the last digit in ticket number */
int dividend;
int remainder = 0; /*remainder is the remainder of (sum of all but last digit) % 7 */
printf("Enter ticket number: ");
while ((ch = getchar()) != '\n') { /* 1 is 49 in ASCII. 0 is 48 in ASCII. 49 - 48 = 1 */
digit = ch - '0'; /* equivalent to ch - 48 */
dividend = (remainder * 10) + digit;
if (dividend >= 7)
remainder = dividend % 7;
else
remainder = dividend;
}
remainder = (dividend - digit) / 10; /* We recover the reminder before using the check digit */
if (remainder == digit)
printf("VALID\n");
else
printf("INVALID\n");
printf("ch: %d\n", ch);
printf("digit: %d\n", digit);
printf("dividend: %d\n", dividend);
printf("remainder: %d\n", remainder);
return 0;
}
```

Airline ticket question.pdf (561 KB)