ValArray Program in C++

This C++ program illustrates the use of valarrays. These are data types designed for efficient numeric computations like scalar multiplication, addition, subtraction, division, modulus, bit-shifting and all sorts of numerical computations. The program initializes a valarray and constructs another from the same valarray. Operations like scalar addition and bit-shifting have been performed on these 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 Illustrate use of ValArrays
  3.  */
  4. #include <iostream>
  5. #include <valarray>
  6.  
  7. void print(std::valarray <int> v)
  8. {
  9.     std::cout << "Valarray = { ";
  10.     for (int i = 0; i < v.size(); i++)
  11.         std::cout << v[i] << "  ";
  12.     std::cout << "}" << std::endl;
  13. }
  14.  
  15. int main()
  16. {
  17.     int array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  18.     std::valarray <int> v(array, sizeof(array) / sizeof(int));
  19.  
  20.     print(v);
  21.     v = v << 1;
  22.     std::cout << "After bit-shifting by 1 :"
  23.               << std::endl; 
  24.     print(v);
  25.     v = v + 1;
  26.     std::cout << "After adding 1 to all elements of valarray :"
  27.               << std::endl;
  28.     print(v);
  29. }

$ a.out
Valarray = { 1  2  3  4  5  6  7  8  9  10  }
After bit-shifting by 1 :
Valarray = { 2  4  6  8  10  12  14  16  18  20  }
After adding 1 to all elements of valarray :
Valarray = { 3  5  7  9  11  13  15  17  19  21  }

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.