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.
/*
* C++ Program to Illustrate use of ValArrays
*/
#include <iostream>
#include <valarray>
void print(std::valarray <int> v)
{
std::cout << "Valarray = { ";
for (int i = 0; i < v.size(); i++)
std::cout << v[i] << " ";
std::cout << "}" << std::endl;
}
int main()
{
int array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
std::valarray <int> v(array, sizeof(array) / sizeof(int));
print(v);
v = v << 1;
std::cout << "After bit-shifting by 1 :"
<< std::endl;
print(v);
v = v + 1;
std::cout << "After adding 1 to all elements of valarray :"
<< std::endl;
print(v);
}
$ 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]Related Posts:
- Practice Computer Science MCQs
- Apply for Computer Science Internship
- Check C++ Books
- Practice Programming MCQs
- Apply for C++ Internship