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

Popular posts from this blog

88: Using switch statement Write a C program to input marks of five subjects Physics, Chemistry, Biology, Mathematics and Computer. Calculate percentage and grade according to following: // Percentage >= 90% : Grade A Percentage >= 80% : Grade B Percentage >= 70% : Grade C Percentage >= 60% : Grade D Percentage >= 40% : Grade E Percentage < 40% : Grade F

205: Book Catalog: Define a struct to represent a book with attributes like title, author, and publication year. Write a program to create a catalog of books by taking user input and display books published after a certain year.

15: Take input of age and name of 3 people by user and determine oldest and youngest among them with his age. -_-_-_-_-_-_-_-_-(line with spaces input concept)-_-_-_-_-_-_-_-_