view raw
Flakee Flakee - 9 months ago 36
C Question

How to read an integer Array

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 :)


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:

     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