Sum of even numbers and multiplication of odd numbers in a range

2
  

Read two numbers where y is greater than x, calculate the sum of the numbers   pairs of this range of numbers, including the numbers entered;   calculate and show the multiplication of the odd numbers of this   range, including those typed;

 #include <stdio.h>
 #include <stdlib.h>
 #include <locale.h>
 int main ()
 {
 setlocale(LC_ALL, "PORTUGUESE");
 int X=0, Y=0,somapar=0, cont=0, impar;


printf("Insira o VALOR DE X: ");
scanf("%d", &X);
printf("Insira o VALOR DE Y: ");
scanf("%d", &Y);


if (Y>X)
{

   for (cont=X; cont<=Y; cont++)
{
cont;

 if (cont%2==0)
 {
 somapar = somapar + cont;
  }

  else
  { 
  impar = impar * cont;
   }

}
   }
  else
   {
    printf("X não pode ser maior que Y\n");
     }
    printf("A soma dos números pares nesse intervalo é %d\n", somapar);
    printf("A multiplicação dos números impares nesse intervalo é %d\n", impar);

  system ("pause");
   return 0;
     }

Putting 0 for X and 10 for Y, the output shows only the sum of even numbers giving 30, but multiplication gives zero.

    
asked by anonymous 06.07.2017 / 23:42

2 answers

5

The multiplication gives zero because it was not started:

int X=0, Y=0,somapar=0, cont=0, impar;

Once you multiply, you must start impar with the neutral value of multiplication, 1:

int X=0, Y=0,somapar=0, cont=0, impar = 1;

Now it works:

    
06.07.2017 / 23:56
3

I was almost ready when I had to answer. I'm posting anyway since it has code running and more organized and simplified.

The main error was not tr initialized variable impar with value 1. Two things could happen. Have the value 0 and then any multiplication would give 0. OR take any value that was in memory, which would be very wrong and would seem crazy. In C always initialize the variables, unless you know what you are doing.

#include <stdio.h>

int main() {
    int X = 0, Y = 0, par = 0, impar = 1;
    printf("Insira o VALOR DE X: ");
    scanf("%d", &X);
    printf("Insira o VALOR DE Y: ");
    scanf("%d", &Y);
    if (Y <= X) {
        printf("X não pode ser maior que Y\n");
        return 0;
    }
    for (int cont = X; cont <= Y; cont++) {
        if (cont % 2 == 0) {
            par += cont;
        } else { 
            impar *= cont;
        }
    }
    printf("A soma dos números pares nesse intervalo é %d\n", par);
    printf("A multiplicação dos números impares nesse intervalo é %d\n", impar);
}

See running on ideone . And no Coding Ground . Also put it on GitHub for futur reference a.

    
07.07.2017 / 00:16