1

Can I read the array as a whole number and break it into digits. Here is a code of what I am trying to do.

#include <stdio.h>

int main(void)
{
    int d [12],
    first_sum, second_sum, total; 

    printf("Enter the UPC code (11 digits): ");

    scanf("%s", d);

    first_sum = d[0] + d [2] + d [4] + d[6] + d[8] + d[10];
    second_sum = d [1] + d [3] + d [5] + d [7] + d [9];
    total = (3 * first_sum) + second_sum;

    printf("Check digit: %d\n", 9 - ((total - 1) % 10));

    return 0;
}

As you can see I am trying to calculate the Check digit for UPC code. And what I want is to break 11-digit number into 1-digit integers and calculate the Check digit. Please tell me what is my mistake? Hope that you understand my question :)

0

3 Answers 3

3

Can i read the array as a whole number and break it into digits?

Yes you can. Use a char array to read in a string representation of your whole number, then convert each character element of the array into its corresponding numeric value.

int d[11];
char stringArray[12];//11 digit characters, + Null terminator.
scanf("%11s", stringArray); //stringArray now contains a string
                            //representation of your number. 
                            //Important: note the format specifier to 
                            //limit scanf to read only 11 characters.

To convert the string to an integer array use its ASCII value:

for(i=0;i<11;i++)
{
     if(!isdigit(stringArray[i]))return -1;//test input, and leave if not digit
     d[i] = stringArray[i] - '0';//ASCII '0' to '9' have decimal values of 48 to 57 
}
Sign up to request clarification or add additional context in comments.

9 Comments

Don't use 48, use '0'.
If scanning a "string", we ought to tell scanf() how much to read for max, so you want to do "%11s".
Thank you for the answer. A am stiil a noob at programming :). Maybe its right but it s not working in my program. Here is what i wrote
#include <stdio.h> int main(void) { int d [12], first_sum, second_sum, total, i; char stringArray [12]; printf("Enter the UPC code (11 digits): "); scanf("%s", stringArray); for (i = 0; i < 12; i++) { if (!isdigit (stringArray [i])) return -1; d[i] = stringArray[i] - '0'; } first_sum = d[0] + d [2] + d [4] + d[6] + d[8] + d[10]; second_sum = d [1] + d [3] + d [5] + d [7] + d [9]; total = (3 * first_sum) + second_sum; printf("Check digit: %d\n", 9 - ((total - 1) % 10)); return 0;
for 11 digits, the loop should be like for(i=0;i<11;i++), not for(i=0;i<12;i++)
|
3

There are many possibilities of doing this. Here is one more way to do it that doesn't use strings, though I like the way using strings. What I am doing here is summing those digits that are in even places from backwards into first_sum, and those in odd places into second_sum, just as in the OP's code.

#include <stdio.h>

int main() {
    long long input;
    int first_sum=0, second_sum=0, total, i;

    printf("Enter the UPC code (11 digits): ");

    if(scanf("%lld", &input) == 1)
    {
        i = 0;
        while (input)
        {
            if (i % 2 == 0)
                first_sum += input % 10;
            else
                second_sum += input % 10;
            input /= 10;
            i++;
        }
    }

    total = (3 * first_sum) + second_sum;

    printf("Check digit: %d\n", 9 - ((total - 1) % 10));

    return 0;
}

A little visual aid:

Here i is the loop counter, that goes from 0 to 10 for the 11 digit UPC code, written right to left. Let the 11 digits user input be "12345678901"

i            :  10  9  8  7  6  5  4  3  2  1  0
i % 2        :   0  1  0  1  0  1  0  1  0  1  0
Even/Odd     :   E  O  E  O  E  O  E  O  E  O  E
Input digits :   1  2  3  4  5  6  7  8  9  0  1

As you can see, for values of i for which i % 2 == 0, the corresponding digits are considered to be in Even (E) places, and are summed to first_sum. And for i % 2 == 1 case, the corresponding digits are considered to be in Odd (O) places, and are summed to second_sum.

So first_sum ends up being "1 + 3 + 5 + 7 +9 + 1", and second_sum being "2 + 4 + 6 + 8 + 0". Hope that makes it clearer.

8 Comments

while (input) might be a bit less error prone then for (i = 0; i < 11; ++i).
Also whether ld works for long long depends on the implementation.
Since the OP said the input is going to be 11 characters... but still, I have edited.
However 1+ for the most sane approach, that is treating numbers as numbers, and not go via strings. All that's still missing it to check whether scanf() actually did read a number.
Also you might want to fix/clean-up this i stuff ... :-S
|
1

Remembering that a string is an array of characters, you could read the user input in as a string, and then do your processing. There are a few gotcha's that you need to be aware of.

Note: All code example that follow have been compiled using gcc version 4.8.3, The command line was: gcc -g -std=c11 -pedantic -Wall temp.c -o temp, and the host platform was Windows 7.

Consider the following snippet:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char   upc[12];

    printf("Enter the UPC code (11 digits):");
    scanf("%11s", upc);

    printf("upc[0]: %c\n", upc[0]);
    printf("upc[2]: %c\n", upc[2]);

    return 0;
}
  1. First notice that I specify a width parameter in the scanf format-string so I do not overflow the upc buffer. It is always a good idea to program defensively, and always validate user input (NB: I have not fully validated the user input in the above, see below for
    complete validation).
  2. If I run this program, shown below, notice that the values of upc[0] and upc[2] are. This means that what we would consider the least significant digit (the ones digit) of the UPC is stored in the 10-th element of the array, while what we consider the most significant digit is stored in the zeroth element of the array. This may or may-not be an issue for you, you can either adjust your formulae or reveres the entered string.

    Q:\>temp 
    Enter the UPC code (11 digits):12345678901
    upc[0]: 1
    upc[2]: 3
    upc is: 12345678901
    

Now for full input validation, these are the things that we need to check,

  1. That the string is exactly 11 characters long.
  2. That the string only contains digits.
  3. That the string doesn't exceed a total length (including null terminator) of 12. This is done for us by the width in the format string

The first is simple, just check the length of the string, if it is not equal to 11 give an error and exit the program. For the second condition, we need to look at every element of the string and check to see if it is a digit. The following contains all the input validation checking:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <ctype.h>

bool isDigit(char*);

int main()
{
    char   upc[12];

    printf("Enter the UPC code (11 digits):");
    scanf("%11s", upc);

    if(strlen(upc) == 11) 
    {
        if(isDigit(upc)) 
        {
           // perform your calculations here
        } 
        else 
        {
            printf("The UPC must contain only digits\n");
        }
    }
    else
    {
        printf("The UPC must be exactly 11 digits long\n");
    }

    return 0;
}

bool isDigit(char* upc)
{
    bool   bRet = true;

    for(int ndx = 0; ndx < strlen(upc); ndx++)
    {
        if(!isdigit(upc[ndx]))
        {
            bRet = false;
            break;
        }
    }

    return bRet;
}

1 Comment

I think you should only post the answer that just solves the OP's problem, and not add any extra details that the OP possibly doesn't need.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.