C++ Program to Check ISBN is Valid or Not

Problem:

Write a class Book with data members to store title of book, number of authors, ISBN number, price and number of copies. Title and ISBN are pointer to characters. Also define parameterized and default constructors (by default number of authors and number of copies equal to 1). Also write a copy constructor. Write getter and setter functions for accepting and displaying the data.

Check validity of ISBN. If ISBN is 10 digit then multiply each digit by its corresponding position and add all multiplications, if this sum is divisible by 11 then ISBN is valid. For a 13 digit ISBN multiply even position digits with 3 and odd position with 1 , add all to sum, if this sum is divisible by 10 then ISBN is valid.

C++ program / Solution:

Here is the source code of C++ program to check ISBN is correct or not for a book.
/* Aim: Write a C++ program to check ISBN is valid or not for a book */

#include<iostream>
#include<string.h>
using namespace std;

class Book
{
 char title[20];
 int ta,nc;
 float price;
 char ISBN[13];

 public:

//Default constructor
 Book()
 {
 ta=1;nc=1;
 }

//Copy constructor
 Book(Book &b)
 {
 strcpy(title,b.title);
 ta=b.ta;nc.b.nc;price=b.price;
 strcpy(ISBN,b.ISBN);
 }

//Parameterized constructor
 Book(char t[20],char isbn[13],int x, int y,float pric)
 {
  strcpy(title,t);
  ta=x;nc=y;price=pric;

  if(isValid(isbn))
  {
   cout<<" Valid ISBN \n \n";
   strcpy(ISBN,isbn);
  }
  else
   cout<<" Invalid ISBN";
  
 }

// function to display data
 void getter();
// function to accept data
 void setter(char t[10], char isbn[10],int x, int y,float pric);
// function to check if ISBN is valid or not
 int isValid(char isbn[13]);
  
};

void Book :: getter()
{
 cout<<" Title: "<<title<<endl;
 cout<<" ISBN: "<<ISBN<<endl;
 cout<<" Price: "<<price<<endl;
 cout<<" No of copies: "<<nc<<endl;
 cout<<" No of Authors: "<<ta<<endl;
}

void Book :: setter(char t[10], char isbn[10],int x, int y,float pric)
{
 strcpy(title,t);
 
 if(isValid(isbn))
 {
  cout<<" \n Valid ISBN \n \n";
  strcpy(ISBN,isbn);
 }
 else
  cout<<"\n Invalid ISBN";

 ta=x;nc=y;price=pric;
}


int Book :: isValid(char isbn[13])
{
 int i,len=strlen(isbn),d,sum=0;

 if(len==10)
 {
  for(i=0;i<len;i++)
  {
   d=isbn[i]-'0'; 
   sum=sum+d*(i+1);
  }

  if(sum%11==0)
   return 1;
  else
   return 0;
 }
 

 if(len==13)
 {
  for(i=0;i<len;i++)
  {
   d=isbn[i]-'0';
   
   if(i%2==0) // odd position
    sum+=d*1;
   else
    sum+=d*3;
  }

  if(sum%10==0)
   return 1;
  else
   return 0;
 }
 
 return 0;
}

int main()
{
 Book b1("Manan","0306406152",4,10,1000.12),b2
;

 b1.getter();
 b2.setter("Chinmay","9783161484100",4,5,100.12);
 b2.getter();
}

/* Output of above code:-

 Valid ISBN 
 
 Title: Manan
 ISBN: 0306406152
 Price: 1000.12
 No of copies: 10
 No of Authors: 4
 
 Valid ISBN 
 
 Title: Chinmay
 ISBN: 9783161484100
 Price: 100.12
 No of copies: 5
 No of Authors: 4

*/