How do I check indices of a given integer number manually?
For example,
I have an 13 digit number (EAN number). I want to check the indices and determine whether they are even or not. Should I turn it into a an array check for indices? I’m a bit lost.
If I turn it to an array, and each element of the array is one of the digits of the number, then that would work. But I don’t know how to do that? Is such thing possible?
So far I’ve writen;
#include <stdint.h>
int ean13(uint64_t ean) {
char x = ean + '0';
int count;
int index;
for (int i = 0; i < count; i++){
index = i;
if (index % 2 == 1){
index /= 3;
}
}
After checking for indices, I will multiply digits with odd indices by 3, that’s what I tried to do in the code with “*3” but I’m finding it hard to conceptualize the checking for digits part.
AStudent is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
17
Here’s how you can extract digits from a number:
int number = 3189;
int even = 0;
int odd = 0;
while (number != 0) {
int digit = number % 10; // Extract the last digit
if (digit % 2 == 0) // check if digit is even
even++;
else
odd++;
number = number / 10; // Remove the last digit
}
I am assuming that given number is in integer and you are only concerned about finding number of even and odd digits.
Quick dry run:
3189
Iteration1:
digit = 9
even = 0, odd = 1
number = 318
Iteration2:
digit = 8
even = 1, odd = 1
number = 31
Iteration3:
digit = 1
even = 1, odd = 2
number = 3
Iteration4:
digit = 3
even = 1, odd = 3
number = 0
7
Simpler to convert to a string with sprint()/snprint()
(even better if input is taken in the form of a string):
char str[/* Some max limit that would be enough */];
sprintf(str, "%d", /* Some integer literal or variable */); /* Use the proper format specifier if it is not an `int` */
// Now you can iterate through the characters and do your processing.
Then each digit value is array[i] - '0'
. – @Weather Vane
Though, have you checked whether an int
can hold 13 digits? I’d suggest using uint64_t
/uintmax_t
or some other type.