C++ Program to Perform Mathematical Operation on Valarray Elements

«
»
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.

  1. /*
  2.  * C++ Program to Apply Mathematical Operation on Elements of a Valarray
  3.  */
  4.  #include <iostream>
  5.  #include <valarray>
  6.  #include <cmath>
  7.  
  8. void print(std::valarray <double> v)
  9. {
  10.     std::cout << "Valarray = { ";
  11.     for (int i = 0; i < v.size(); i++)
  12.         std::cout << v[i] << "  ";
  13.     std::cout << "}" << std::endl;
  14. }
  15.  
  16.  int main()
  17.  {
  18.      std::valarray<double> v(1, 5);
  19.      std::valarray<double> v2 = v + v;
  20.      std::valarray<double> v3 = 5.0 * v2;
  21.      std::valarray<double> v4 = cos(v3);
  22.  
  23.      print(v);
  24.      std::cout << "Adding two valarrays " << std::endl;
  25.      print(v2);
  26.      std::cout << "Multiplying elements with a double " << std::endl;
  27.      print(v3);
  28.      std::cout << "Computing cosine of all elements " << std::endl;
  29.      print(v4);
  30.  }

$ 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.

Note: Join free Sanfoundry classes at Telegram or Youtube
advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.