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

4

How do I multiply values of a vector of integers by each other in C. I have values inside an array eg [1,2,3,4], I want to multiply one by the other, resulting in 24. p>     

asked by anonymous 12.02.2014 / 18:02

3 answers

8

Just use a for loop to go through the array and multiply the elements one at a time in 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];
}
    
12.02.2014 / 18:09
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);
    
08.03.2014 / 14:59
0

Make a repeat loop by traversing the entire array, create an integer type variable to store the result, and multiply it by the value in the array index .....

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);
}
    
08.07.2016 / 21:59