/* Name: upc2.c Purpose: Computes UPC check digit. Author: Bill Slough Notes: Loosely based on upc.c (King, Chapter 4, page 57) */ #include #include #define NDIGITS 11 /* number of digits in a UPC code */ #define EVEN_WT 3 /* weight for digits in even-numbered positions */ #define ODD_WT 1 /* weight for digits in odd-numbered positions */ int checkDigit(long code); int main(void) { long upcCode; /* Assumes the long data type can hold 11-digits */ printf("Enter the UPC code: "); scanf("%ld", &upcCode); printf("Check digit: %d\n", checkDigit(upcCode)); return 0; } int checkDigit(long code) { /* computes the checksum of a UPC, given its 11-digit code code = d_10 d_9 d_8 ... d_2 d_1 d_0 */ int i; /* loop index */ bool evenIndex; /* even or odd digit position? */ int digit; /* current digit to process */ int sum; /* running weighted sum */ /* compute the weighted sum of the digits, processing the digits from right to left */ evenIndex = true; sum = 0; for (i = 0; i < NDIGITS; i++) { /* get the least significant digit */ digit = code % 10; /* process this digit */ if (evenIndex) sum += EVEN_WT * digit; else sum += ODD_WT * digit; /* flip the index position */ evenIndex = !evenIndex; /* right shift the code one digit */ code /= 10; } /* return the check digit */ return 9 - (sum - 1) % 10; }