There are some ways to do it, there’s the most confusing and the smartest, that I’ve preferred:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void parImpar (int num) {
int digitos = floor(log10(abs(num))) + 1;
for (int i = digitos - 1; i >= 0; i--) {
int div = num / (int)pow(10, i);
num = num % (int)pow(10, i);
printf(div % 2 == 0 ? "\n%d eh Par" : "\n%d eh Impar", div);
}
}
int main() {
int num;
printf("Digite um numero inteiro: ");
scanf("%d", &num);
parImpar(num);
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
First he discovers the number of digits through a known formula. There are other ways to get this, but I don’t like any.
Then we make a loop knowing where it starts and where it ends. And in it we do the account to get the value of the digit by dividing by the power of 10 to the position you are analyzing. And then you take the rest of that room to keep doing the same with the other digits.
For example: the first power will result in 10000 (10 4) so dividing 12345 by 10000 gives 1 and this is can be analyzed whether it is even or odd. Then you take the rest of this which is 2345 and which will be divided by 1000, then you give 2, and then over 345 divided by 100 which gives 3, and over 45 divided by 10 gives 4 and finally 5 divided by 1 gives 5.
Not clear. Is the idea to check number by number of a number? Example:
255 | 2, 5 e 5
?– Renan Gomes
@Renan exactly that, Renan!
– Henrique Tavares
@Leocaracciolo I don’t understand C++, either, Leo! But it seems more complicated than it looks.
– Henrique Tavares