Analyze whether a number is even or odd

6

The program should do:

Digite um Número: 12345 

1 e ímpar  
2 e par  
3 e ímpar  
4 e pra  
5 e ímpar

So far I've made the following code:

void parImpar (int num) {      
    int resto;
    while (num > 0) {
        resto = num%10;
        if(resto%2==0) {
            printf("\n%d eh Par", resto);
        } else {
            printf("\n%d eh Impar", resto);
        }
        num = num / 10;
    }

}

int main(int argc, char** argv) {
    int num;
    printf("Digite um numero inteiro: ");
    scanf("%d",&num);
    parImpar(num);        
}

This code returns the inverse:

Digite um Número: 12345 

5 e ímpar  
4 e par  
3 e ímpar  
2 e pra  
1 e ímpar
    
asked by anonymous 31.08.2018 / 05:03

1 answer

6

There are some ways you can do this, the most confusing and the most intelligent, which I 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);        
}

See running on ideone . Also put it on GitHub for future reference .

First he discovers the number of digits through a known formula. There are other ways to get this, but I do not like any.

Here we make a loop knowing where it begins and where it ends. And in it we make the count to get the value of the digit dividing by the power of 10 raising to the position that is analyzing. And then get the rest of this division to continue doing the same with the other digits.

Exemplifying: The first power will result in 10000 (10 ^ 4) so divide 12345 by 10000 gives 1 and this can be analyzed if it is even or odd. Then you get the rest of this that gives 2345 and that will be divided by 1000, then give 2, then over 345 divided by 100 that gives 3, and over 45 divided by 10 gives 4 and finally 5 divided by 1 gives 5.

    
31.08.2018 / 05:56