157: Check if the barcode is valid or not. The final digit of a Universal Product Code is a check digit computed so that sum of the even positions number, plus 3 multiplies with the sum of odd positioned numbers, modulo 10 = 0. // 036000 291452 // For example, in your program take the UPC as 7 digits number i.e. 4708874. The sum of even positioned digits is 7+8+7 = 22, and the sum of the odd-numbered digits is 4+0+8+4 = 16. The total sum is 22+3×16 = 70 = 0 modulo 10. So, the code is valid
// Check if the barcode is valid or not
// The final digit of a Universal Product Code is a check digit computed so that sum of the
// even positions number, plus 3 multiplies with the sum of odd positioned numbers, modulo 10 = 0.
// 036000 291452
// For example, in your program take the UPC as 7 digits number i.e. 4708874. The sum of even
// positioned digits is 7+8+7 = 22, and the sum of the odd-numbered digits is 4+0+8+4 = 16. The total
// sum is 22+3×16 = 70 = 0 modulo 10. So, the code is valid
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "Muhammad Umar Chaudhry" << endl;
cout << "SU92-BSCSM-S23-007" << endl;
cout << "Question # 18" << endl
<< endl;
string barcode;
int even_sum = 0, odd_sum = 0;
cout << "Enter the barcode: ";
cin >> barcode;
int size = barcode.size();
for (int i = 1; i <= size; i++) // i started with 1 to check even and odd positions
{
int a = barcode.at(i - 1) - 48; // (i - 1) to get index
// you can also do (-'0') in place of (- 48) because you are minusing the ascii value of
// character 0 from char you get from string at i position
if (i % 2 == 0)
{
even_sum += a;
}
else
{
odd_sum += a;
}
}
if (((even_sum + 3) * odd_sum) % 10 == 0)
{
cout << "The barcode: (" << barcode << ") is valid\n"
<< endl;
}
else
{
cout << "The barcode: (" << barcode << ") is invalid\n"
<< endl;
}
return 0;
}
Comments
Post a Comment