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

Asked

Viewed 6,394 times

2

Read two numbers being y greater than x, calculate the sum of the numbers pairs of that range of numbers, including the numbers typed; 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 to X and 10 to Y, the output shows only the sum of even numbers that gives 30, but the multiplication gives zero.

2 answers

5


Multiplication gives zero because it has not started:

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

Once it will multiply it should start the impar with the neutral multiplication value, 1:

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

Now it works:

inserir a descrição da imagem aqui

  • I thought I already tried that kkkkkkkkkk was, thanks!!!

3

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

The main error was not initializing the variable impar with value 1. Two things could happen. To have the value 0 and then any multiplication would give 0. Or to take whatever value was in the memory, which would go very wrong and would seem crazy. In C always initialize variables, unless you know what you’re 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);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • I had initialized all the variables, but everything was equal to 0. And I gave what you said, the multiplication output was 0. I even tried to put odd = 1, but I think when I did this there was more than one error and so tbem gave 0. kkkkkkkk In the end it was all right. Thanks for the explanation!

Browser other questions tagged

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