How to calculate the product of the elements of an array in C

Asked

Viewed 8,769 times

4

How do I multiply values of an integer vector by each other in C. I have values within an array for example [1,2,3,4], I want to multiply one by the other, resulting in 24.

  • 2

    In C or Java? What have you done? Elaborate more on your question.

  • It’s in C had put the wrong tag already fixed.

4 answers

10

Just use a for loop to traverse the array and multiply the elements one at a time on an accumulator. The initial value of the accumulator is 1 because this is the neutral element of multiplication.

int array[] = {1,2,3,4};
int produto = 1, i;
for (i = 0; i < 4; i++) {
    produto *= array[i];
}
  • Yes I’m using the loop, ok, need this neutral element was worth the force.

  • 4

    Or you can initialize the product with the first array value and start iterating the array from position 1

  • 1

    @Joaoraposo but Victor’s solution is the most didactic, which seems appropriate by the level of the question.

  • 1

    Thanks for the answers and also found the answer of the most didactic Victor.

  • @fotanus I will have to agree with you, my suggestion reflects what happens in the day to day but it is not Dida'tica at all.

0

To multiply and sum the elements of an array is basically to make a succession of terms.

We have the following: ////////////////

int *vector = {1,2,3,4};
int i, total = 0;
/*Realizar a primeira iteracao da sucessao*/
total = vetor[0];
/*Fazer um ciclo a começar em i=1*/
for(i=1; i<4; i++){
   total = total * vetor[i];
}
printf("Total: %d", total);
  • wrong, you are adding up the value of the multiplications.

0

Loop through the entire array, create an integer type variable to store the result, and multiply it by the value that is in the array’s Dice.....

int main(){
    int vetor[4] = {1,2,3,4};
    int total = vetor[0];
    total = vetor[0];
        for(int i=1; i<4; i++){
            total = total * vetor[i];
        }
    printf("%d", total);
}
  • 1

    wrong, you are adding up the value of the multiplications.

  • 1

    It was wrong to initialize the total variable, which was starting at zero, but the repetition loop is correct.

  • Now it is correct, but when I had viewed it I was assigning the result + the value was already in the total variable (as well as in the @Urb response ).

  • '~' I hadn’t used IDE, but thank you anyway.

0

int mmc = 1;
for (int m = 0; m < divisor.Count; m++)
{
     mmc = mmc *divisor[m];
}

Start the variable with 1, so it will multiply by itself and next can multiply, if start with zero it will never be less than zero.

I did it this way and it worked.

Browser other questions tagged

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