Sum of N first pairs and product of N odd first

2

I have a problem with the following java exercise, I'm starting with the language:

Make a program that calculates and shows the sum of the first N even numbers and the product of the first N odd numbers simultaneously, where N is a number that is entered by keyboard.

How could this exercise be done?

I got here, but when I give it I get the results of the multiplications in 0

int contador = 0;
int contador1 = 0; 
int i = 0;
int j = 1;
for (i=0; i <= num; i++) {
    if (i % 2 == 0) {
        contador +=i;
        System.out.println(contador);
    }
}   System.out.println("\n");
for (j=1; j <= num; j++) {
    if (j % 2 !=0) {
        contador1 *=j;
        System.out.println((double)contador1);
    }
}
    
asked by Vlad T 06.10.2017 в 22:21
source

3 answers

0

Look I have done an exercise with what you ask, it is easy to understand but any questions, the only thing you should do as they say in the comments is to ask if (variable %2 == 0) to know if it is even, with an else already valid which are odd and you make the product of the odd

Code:

public class Main 
{    
    public static void main(String[] args)
    {
        Scanner tecla = new Scanner (System.in);
        int numero ,inicial = 1 ,suma = 0,producto = 1;

        System.out.print("Introduce un numero: ");
        numero = tecla.nextInt();

        while(inicial < numero)
        {
            if(inicial%2==0)
            {
                suma = suma + inicial;
            }
            else
            {
                producto = producto * inicial;
            }
            inicial++;
        }

        System.out.println("\n La suma de los numero pares es: "+suma);
        System.out.println("\n El producto de los numeros impares es: "+producto);
    }
}
    
answered by 06.10.2017 / 22:56
source
1

The problem is that you initialize the counter variable 1 to 0, so all the multiplications result in 0.

int contador = 0;
int contador1 = 1;  //inicializamos contador1 a 1 
int i = 0;
int j = 1;
for (i=0; i <= num; i++) {
   if (i % 2 == 0) {
       contador +=i;
       System.out.println(contador);
}
}     System.out.println("\n");
for (j=1; j <= num; j++) {
    if (j % 2 !=0) {
        contador1 *=j;
        System.out.println((double)contador1);
    }
}

Also, you should keep in mind that you do not need to have two for, since you only need one to go through all the numbers (if a number is not even, then it will be odd).

    
answered by 06.10.2017 в 23:05
-1

Try the following code, I have not tried it but it would basically go like this:

int num = 10;
int cont1=0;
int cont2=1:

for(i=0;i<num;i++){ 
if ((i % 2) == 0){ 
cont1 = cont1 + i; 
System.out.println(contador); 
}else{ 
cont2 = cont2 * i; 
System.out.println(contador1); 
} 
    
answered by 06.10.2017 в 22:50