multiplying all values of an array

Nov 16, 2013 at 1:33am
Hello. I have an array as such and need to multiply all the values of it by each other and put that as a variable.
1
2
3
4
5
6
//for example
int array1[100]
//assume i have already input the values of each element properly up to, say, element 4 
//I need to now multiply all of those values together. I think I need the size of the array to control 
//what it multiplies(I know how to find size) If anyone could give an example code snippet of how
//to do what I asked, that would be great. Thanks everyone in advance! 
Nov 16, 2013 at 1:54am
1
2
#include <functional>
#include <numeric> 

 
int product = std::accumulate( std::begin(array1), std::end(array1), 1, std::multiplies <int> () );

Enjoy!
Nov 16, 2013 at 1:00pm
Thank you but there is a slight problem. end and begin are not part of std and when I remove the std:: it says that they are not declared in this scope.
Nov 16, 2013 at 4:28pm
Sorry.

#include <iterator>

If that doesn't work then your compiler is not up to date.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <cstddef>

template <typename T, size_t N>
const T* begin( const T(&a)[ N ] )
  {
  return (T*)a;
  }

template <typename T, size_t N>
const T* end( const T(&a)[ N ] )
  {
  return (T*)a + N;
  }

Hope this helps.
Nov 17, 2013 at 12:55am
Duoas, thank you for your help. I thought my methods were flawed. I just did
1
2
for(;a < numberofelements;a++)
overallnum*=array1[a]

As it turns out, I made a little error in the numberofelements integer. Thank you though. I didn't understand much of what you gave. I'm not thst advanced yet. Thank you! P.S. My program is finally complete!
Topic archived. No new replies allowed.