Exercise with even and odd C

2

Statement - Make an algorithm that reads a set of numbers (X) and indicates the number of even numbers (QPares) and the number of odd numbers (QImpares) read.

Note: Entry of values ends when the user enters 0.

      #include <stdio.h>
      main(){
      int num,res,qpar=0,qimp=0;
      while(num!=0){
      printf("Introduza");
      scanf("%d",&num);
        res=num%2;
       if(res==0){
        qpar++;
    } else {
        qimp++;
    }
   }
  printf("Pares -> %d\n",&qpar);
  printf("Impares -> %d\n",&qimp);
}

I do not know what I'm doing wrong in this, it compiles well but the problem is it does not give me the right values of even and odd numbers. For the rest he is also doing the cycle correctly.

    
asked by anonymous 22.11.2016 / 16:21

3 answers

1

There are errors, & is not used to print. One more conditional to validate before zero so it does not come in as even.

Code

  #include <stdio.h>
  int main(){
      int num,qpar=0,qimp=0;
      float res;
      do{
          printf("Introduza");
          scanf("%d",&num);
          if(num!=0){ //Condicional para que  o 0 não conte como par    
              res=num%2;        

              if(res==0){
                  qpar++;
              } else {
                  qimp++;
              }
          }
      }while((num!=0));
      printf("Pares -> %d\n", qpar); //Retirado o &
      printf("Impares -> %d\n", qimp); //Retirado o &
  }
    
22.11.2016 / 16:31
1

Your error is here:

    printf("Pares -> %d\n", &qpar);
    printf("Impares -> %d\n", &qimp);

Take out these & . You do not want to show the addresses of the variables, but the values. What you want is this:

    printf("Pares -> %d\n", qpar);
    printf("Impares -> %d\n", qimp);
    
22.11.2016 / 16:30
1

Organizing the code helps identify the problem. In the specific case, you are prompted to print an integer pointer instead of an integer. If it were compiled as it should, it would not even compile. and an error would appear.

scanf() needs to pass a pointer, so it uses the & ( address of ) because it needs to say where the read value of the keyboard will be stored. no printf() should not do this, it is the very value that you want to print, not the address where it is.

#include <stdio.h>

int main() {
    int num = 1, qpar = 0, qimp = 0;
    while (num != 0) {
        printf("Introduza\n");
        scanf("%d", &num);
        if (num % 2 == 0) {
            qpar++;
        } else {
            qimp++;
        }
    }
    printf("Pares -> %d\n", qpar);
    printf("Impares -> %d\n", qimp);
}

See working on ideone and on CodingGround .

    
22.11.2016 / 16:30