Analyze whether a number is even or odd

Asked

Viewed 2,353 times

7

The program must 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 me the reverse:

Digite um Número: 12345 

5 e ímpar  
4 e par  
3 e ímpar  
2 e pra  
1 e ímpar
  • Not clear. Is the idea to check number by number of a number? Example: 255 | 2, 5 e 5?

  • @Renan exactly that, Renan!

  • @Leocaracciolo I don’t understand C++, either, Leo! But it seems more complicated than it looks.

1 answer

6


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.

  • Fantastic! That’s exactly what it was! Thanks for the explanation!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.