Anthino Russo - 1 year ago 46

C Question

I'm a beginner and I'm trying to create a program that will generate numbers made only from even digits, rounding up to the nearest such number.

Examples:

135 --> 200

2700 --> 2800

I have one code but whenever I try to print it, the number increments only for 1 because I print it in the

`while`

Here's the code, check it out.

`#include <stdio.h>`

#include <stdlib.h>

int main() {

int a = 135;

int cifra;

int i = a;

int n;

while (i != 0) {

cifra = i % 10;

n = cifra;

if (n % 2 == 0) {

i /= 10;

} else {

++a;

}

}

return 0;

}

Answer Source

Your solution does not work because you may need to propagate the oddness up by several powers of 10.

Here is a simple method:

- check each digit from the least significant to the most significant ;
- for every odd digit, bump the number to the next multiple of the corresponding power of 10. A pattern of
`xx1yyy`

becomes`xx2000`

and a pattern of`x9yyy`

becomes`X0000`

where`X`

may be odd and will be handled in the next iteration.

Here is the code:

```
#include <stdio.h>
#include <stdlib.h>
unsigned next_even(unsigned n) {
for (unsigned div = 1; div <= n; div *= 10) {
unsigned digit = (n / div) % 10;
if (digit & 1) {
/* found an odd digit, bump number up to the
next multiple of div */
n = n - n % div + div;
}
if (div > UINT_MAX / 10) {
/* Prevent wrap around.
The result may be incorrect for numbers >= UINT_MAX / 10. */
break;
}
}
return n;
}
int main(int argc, char *argv[]) {
for (int i = 1; i < argc; i++) {
unsigned n = strtoul(argv[i], NULL, 0);
printf("%u -> %u\n", n, next_even(n));
}
return 0;
}
```

Note that the above method does not work for all unsigned values because of potential overflow.