This C++ program illustrates the application of mathematical operation to valarrays. The elements of valarray are initialized to an int. The program adds two valarrays, performs scalar multiplication with valarrays and computes value of trigonometric ratio of each element of valarrays.
Here is the source code of the C++ program illustrates the use of valarrays. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C++ Program to Apply Mathematical Operation on Elements of a Valarray
*/
#include <iostream>
#include <valarray>
#include <cmath>
void print(std::valarray <double> v)
{
std::cout << "Valarray = { ";
for (int i = 0; i < v.size(); i++)
std::cout << v[i] << " ";
std::cout << "}" << std::endl;
}
int main()
{
std::valarray<double> v(1, 5);
std::valarray<double> v2 = v + v;
std::valarray<double> v3 = 5.0 * v2;
std::valarray<double> v4 = cos(v3);
print(v);
std::cout << "Adding two valarrays " << std::endl;
print(v2);
std::cout << "Multiplying elements with a double " << std::endl;
print(v3);
std::cout << "Computing cosine of all elements " << std::endl;
print(v4);
}
$ a.out Valarray = { 1 1 1 1 1 } Adding two valarrays Valarray = { 2 2 2 2 2 } Multiplying elements with a double Valarray = { 10 10 10 10 10 } Computing cosine of all elements Valarray = { -0.839072 -0.839072 -0.839072 -0.839072 -0.839072 }
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.
Related Posts:
- Practice Programming MCQs
- Apply for C++ Internship
- Practice Computer Science MCQs
- Check Computer Science Books
- Check C++ Books