Array Multiplication Using For Loop

Hey everyone, I am wondering how to multiply the values of an array together using a for loop. For example:

 
  int array[5] = {2, 3, 4, 5, 6};


How can I get the result of 2 * 3 * 4 * 5* 6 using a for loop?

Thanks in advance!
1
2
3
4
5
6
7
8
9
10
int multiplyArray(int arr[], int len) {
    //Initialize with 1, not 0 because 0 * anything = 0
    int result = 1;
    //cycle though the values
    for(int i = 0; i < len; i ++) {
        //multiply the last result by the current element
        result *= arr[i];
    }
    return result;
}

Hope this helps :)
1
2
3
4
for(int i = /* First index */; i < /* Last index */; i++) {
// Use an extra variable to keep the 'sum' of the previous multiplications
// *Hint* The first iteration would need to be handled differently than the others since array[i-1] would be invalid
}
Last edited on
Thank you so much for the help! :)
Out of curiosity, would it be pretty much the same set-up for division or no? I tried using division but no matter what, it's outputting '0'
What do you mean by "for division"? Do you mean if we have int arr[5] = {a, b, c, d, e} the output should be a/b/c/d/e?
Yes, that's what I mean.
Out of curiosity, would it be pretty much the same set-up for division or no? I tried using division but no matter what, it's outputting '0'

Integer division truncates the fractional part. Change the array type to a float or a double.
The basic idea would be the same, but like integralfx said, change the array type, and also the return type & the type of the variable that stores the current result to a floating-point variable type (i.e.float,double, and long double)
Topic archived. No new replies allowed.