c++ product of vector
C++ Product of Vector
To calculate the product of a vector in C++, you can iterate over the elements of the vector and multiply them together. Here's an example code snippet that demonstrates this:
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {2, 4, 6, 8};
int product = 1;
for (int num : numbers) {
product *= num;
}
std::cout << "Product: " << product << std::endl;
return 0;
}
Explanation:
1. We include the necessary headers: <iostream>
for input/output operations and <vector>
for using vectors.
2. We define a vector called numbers
and initialize it with some values.
3. We initialize a variable called product
to 1. This variable will store the product of the vector elements.
4. We use a range-based for loop to iterate over each element num
in the numbers
vector.
5. Inside the loop, we multiply the current value of product
by num
and update the value of product
.
6. After the loop, we print the value of product
using std::cout
.
Output:
Product: 384
Note: This example assumes that the vector contains integer values. If you're working with a vector of a different data type, make sure to adjust the code accordingly.