Home > Blockchain >  Problem from 'C programming a modern approach'
Problem from 'C programming a modern approach'

Time:08-17

Chapter 7 q11:
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. Write a program to test if a ticket is valid.

My code is:

main(){ 

    char c;
    int remainder = 0;
    
    printf("Enter a ticket number: ");
    
    while((c = getchar()) != '\n'){
       c -= '0';
       remainder = (remainder * 10   c) % 7;
    }

    return 0;
}

However I cannot work out how to single out the last digit of the airline number so as to not include it in the remainder calculation and also to use it to validate the ticket.

Any help would be appreciated.

CodePudding user response:

This is what I came up with. I don't think its the best solution but it does work.

int main(void) {

char c;
int remainder = 0;
int i = 0;
char str[20] = "";

printf("Enter a ticket number: ");

while ((c = getchar()) != '\n')
{
    str[i] = c;
    i  ;
}

for (int x = 0;x<i-1;x  )
{       
    remainder = (remainder * 10   (str[x]-'0')) % 7;        
}

if (remainder == (str[i-1]-'0'))
    printf("Valid");
else
    printf("Invalid");


return 0;

CodePudding user response:

You only need to 'buffer' the last two digits entered before the '\n'. (It may be wise to use isdigit() to test validity of each character typed, and to check that at least two digits have been entered.)

To 'juggle' two digits, this presumes a leading '0' (cPrev) has already been entered before the grinding starts. Here's a rough cut.

int main( void ) {
    char cPrev = '0';
    char cCurr = '0';
    int remainder = 0;

    printf( "Enter a ticket number: " );

    int cin;
    while( ( cin = getchar() ) != '\n' && cin != EOF ) {
        cPrev = cCurr;
        remainder = ( remainder * 10   (cCurr - '0') ) % 7;
        cCurr = (char)cin;
    }
    
    if( cin != EOF )
        printf( "%s\n", remainder == cCurr - '0' ? "Valid" : "Invalid" );

    return 0;
}

CodePudding user response:

Firstly, you should store your ticket number in a long long integer because it is lengthy! Then you should store your last digit in a variable and divide the number by 10. Finally you can check if the remainder is equal to last digit.

#include <stdio.h>
int main() {
    long long int ticketNumber;
    int lastDigit;
    int remainder;
    scanf("%lld",&ticketNumber);
    lastDigit = ticketNumber ;
    ticketNumber/=10;
    if(ticketNumber % 7 == lastDigit){
        printf("Ticket is valid!");
    }else{
        printf("Ticket is not valid!");
    }
    return 0;
}
  •  Tags:  
  • c
  • Related