For starters the function should be declared like
long long int mult_while( const int *array, size_t len );
that is the return type should be long long int
to avoid overflowing. And the pointer should be declared with the qualifier const
because the array is not being changed within the function. The size of the array should have the type size_t
,
You need not to declare one more local variable apart from the parameters as it was done in the for loop in your first function implementation.
The function can be implemented the following way using the while loop.
long long int mult_while( const int *array, size_t len )
{
long long int mult = len == 0 ? 0 : 1;
while ( len-- ) mult *= array[len];
return mult;
}
Pay attention to that in general the user can pass the length of the array equal to 0. In this case it will be logically consistent to return 0.
Here is a demonstrative program.
#include <stdio.h>
#include <limits.h>
long long int mult_while( const int *array, size_t len )
{
long long int mult = len == 0 ? 0 : 1;
while ( len-- ) mult *= array[len];
return mult;
}
int main(void)
{
int a[] = { INT_MAX, INT_MAX };
const size_t N = sizeof( a ) / sizeof( *a );
for ( size_t i = 0; i < N; i++ )
{
printf( "%d ", a[i] );
}
putchar( '\n' );
printf( "The product of the array elements is equal to %lld\n", mult_while( a, N ) );
return 0;
}
The program output is
2147483647 2147483647
The product of the array elements is equal to 4611686014132420609
As you can see for such big numbers stored in the array the result is correct.
It is the only function implementation among presented here in answers that is more or less correct.