Skip to main content

arrayalg.cpp


// Demonstration of how algorithms can be used on arrays
// (NDE, 2014-01-07)
#include <iostream>
#include <iterator>
#include <algorithm>
#include <numeric>
using namespace std;
int main()
{
  int x[5] = {1, 4, 9, 16, 25};
  // Display array contents
  cout << "Initial: ";
  ostream_iterator<int> out(cout, " ");
  copy(x, x+5, out);
  cout << endl;
  // Reverse order of array values and display
  reverse(x, x+5);
  cout << "Reversed: ";
  copy(x, x+5, out);
  cout << endl;
  // Sort first three elements and display
  sort(x, x+3);
  cout << "Partial sort: ";
  copy(x, x+5, out);
  cout << endl;
  // Accumulate and display sum of array values
  cout << "Sum = " << accumulate(x, x+5, 0) << endl;
  return 0;
}