C++ Program to Calculate Inner Product of Two Valarrays

This C++ program obtains the inner product of two valarrays. The inner product of two valarrays is defined as the scalar multiplication of each corresponding element of the two valarrays. The result for two valarrays with different sizes is unpredictable and varies from implementation to implementation.

Here is the source code of the C++ program obtains the inner product of two 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 Obtain Inner Product of Two Valarrays
  3.  */
  4. #include <iostream>
  5. #include <valarray>
  6.  
  7. void print(std::valarray <double> v)
  8. {
  9.     for (int i = 0; i < v.size(); i++)
  10.         std::cout << v[i] << "  ";
  11.     std::cout << std::endl;
  12. }
  13.  
  14. int main()
  15. {
  16.     std::valarray <double> v(2, 5);
  17.     std::valarray <double> vd(1.5, 5);
  18.     std::valarray <double> vd2(10.0, 10);
  19.  
  20.     std::cout << "Valarray 1 => ";
  21.     print(v);
  22.     std::cout << "Valarray 2 => ";
  23.     print(vd);
  24.     std::cout << "Inner Product of valarray 1 and 2 => ";
  25.     vd = v * vd;
  26.     print(vd); 
  27.     // Behaviour of multiplying different sized valarrays is undefined
  28.     std::cout << "Inner Product of valarrays of different sizes => ";
  29.     vd = vd * vd2;
  30.     print(vd);
  31. }

$ a.out
Valarray 1 => 2  2  2  2  2
Valarray 2 => 1.5  1.5  1.5  1.5  1.5
Inner Product of valarray 1 and 2 => 3  3  3  3  3
Inner Product of valarrays of different sizes => 30  30  30  30  30

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

If you find any mistake above, kindly email to [email protected]

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 & discussions at Telegram SanfoundryClasses.