C++ program on visual studio. 3. Sorting an array of data Use C++\'s sort() func
ID: 3863050 • Letter: C
Question
C++ program on visual studio.
3. Sorting an array of data Use C++'s sort() function to sort an array of data. Use C++'s accumulate() to sum up an array of values. C++'s sort takes an array of data and sorts itin place. Because C++ arrays don't keep track of their own size, we have to tell sort where our data begins and where it ends. We do this by passing it what amounts to the beginning and end of the data by making use of the fact that an array's name is the same thing as the address of where the array is located in memory double xvals [10 sort (xvals xvals +10) C++'s accumulate() function is similar. You pass it the beginning and end of your data. It also takes a 3rd parameter -an initial value for the sum (which is usually 00 The data type of the initial value determines what arithmetic gets done, though, so you must use 0.0 (instead of integer 0) when adding up doubles. If you pass it an integer by mistake, it will truncate all your values to their integer portion and sum those up (which is probably NOT what you want... The sample program sample sort sum.c will help with this portion of the assignment. Assignment 3:Explanation / Answer
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#include <numeric>
using namespace std;
int main()
{
srand (time(NULL));
double xvals[10];
for(int i=0; i<10; i++){
xvals[i] = rand() % 11 + 10;
}
cout<<"Array elements before sorting: "<<endl;
for(int i=0; i<10; i++){
cout<<xvals[i]<<" ";
}
cout<<endl;
sort(xvals, xvals+10);
cout<<"Array elements after sorting: "<<endl;
for(int i=0; i<10; i++){
cout<<xvals[i]<<" ";
}
cout<<endl;
double sum = accumulate(xvals,xvals+10,0);
cout<<"Sum is "<<sum<<endl;
return 0;
}
Output:
sh-4.2$ g++ -std=c++11 -o main *.cpp
sh-4.2$ main
Array elements before sorting:
10 15 15 16 16 10 14 18 18 16
Array elements after sorting:
10 10 14 15 15 16 16 16 18 18
Sum is 148
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.