108k views
1 vote
python (Business: check ISBN-10) An ISBN-10 (International Standard Book Number) consists of 10 digits: d1d2d3d4d5d6d7d8d9d10. The last digit, d10, is a checksum, which is calculated from the other nine digits using the following formula: (d1 * 1 d2 * 2 d3 * 3 d4 * 4 d5 * 5 d6 * 6 d7 * 7 d8 * 8 d9 * 9) % 11 If the checksum is 10, the last digit is denoted as X according to the ISBN-10 convention. Write a program that prompts the user to enter the first 9 digits and displays the 10-digit ISBN (including leading zeros). Sample Run 1 Enter the first 9 digits of an ISBN as a string: 3601267 Incorrect input. It must have exact 9 digits Sample Run 2 Enter the first 9 digits of an ISBN as a string: 013601267 The ISBN-10 number is 0136012671 Sample Run 3 Enter the first 9 digits of an ISBN as a string: 013031997 The ISBN-10 number is 013031997X

1 Answer

6 votes

Answer:

The programming language is not stated;

However, I'll answer this question using C++ programming language

The program uses few comments; See explanation section for more detail

Also, the program assumes that all input will always be an integer

#include<iostream>

#include<sstream>

#include<string>

using namespace std;

int main()

{

string input;

cout<<"Enter the first 9 digits of an ISBN as a string: ";

cin>>input;

//Check length

if(input.length() != 9)

{

cout<<"Invalid input\\Length must be exact 9";

}

else

{

int num = 0;

//Calculate sum of products

for(int i=0;i<9;i++)

{

num += (input[i]-'0') * (i+1);

}

//Determine checksum

if(num%11==10)

{

input += "X";

cout<<"The ISBN-10 number is "<<input;

}

else

{

ostringstream ss;

ss<<num%11;

string dig = ss.str();

cout<<"The ISBN-10 number is "<<input+dig;

}

}

return 0;

}

Step-by-step explanation:

string input; -> This line declares user input as string

cout<<"Enter the first 9 digits of an ISBN as a string: "; -> This line prompts the user for input

cin>>input; -> The user input is stored here

if(input.length() != 9) { cout<<"Invalid input\\Length must be exact 9"; } -> Here, the length of input string is checked; If it's not equal to then, a message will be displayed to the screen

If otherwise, the following code segment is executed

else {

int num = 0; -> The sum of products of individual digit is initialized to 0

The sum of products of individual digit is calculated as follows

for(int i=0;i<9;i++)

{

num += (input[i]-'0') * (i+1);

}

The next lines of code checks if the remainder of the above calculations divided by 11 is 10;

If Yes, X is added as a suffix to the user input

Otherwise, the remainder number is added as a suffix to the user input

if(num%11==10) { input += "X"; cout<<"The ISBN-10 number is "<<input; }

else

{

ostringstream ss;

ss<<num%11;

string dig = ss.str();

cout<<"The ISBN-10 number is "<<input+dig;

}

}

User Msgmaxim
by
5.9k points