In: Computer Science
"4. (Modify) Modify Program 7.14 so that the user inputs the initial set of numbers when the program runs. Have the program request the number of initial numbers to be entered."
//C++ Program 7.14 as follows
#include
#include
#include
#include
using namespace std;
int main()
{
const int NUMELS = 4;
int n[] = {136, 122, 109, 146};
int i;
vector partnums(n, n + NUMELS);
cout << "\nThe vector initially has the size of "
<< int(partnums.size()) << ",\n and contains the
elements:\n";
for (i = 0; i < int(partnums.size()); i++)
cout << partnums[i] << " ";
partnums[3] = 144;
cout << "\n\nAfter replacing the fourth element, the vector
has a size of "
<< int(partnums.size()) << ",\n and contains the
elements:\n";
for (i = 0; i < int(partnums.size()); i++)
cout << partnums[i] << " ";
partnums.insert(partnums.begin()+1, 142);
cout << "\n\nAfter inserting an element into the second
position, "
<< "\n the vector has a size of " <<
int(partnums.size()) << ","
<< "and contains the elements: \n";
for (i = 0; i < int(partnums.size()); i++)
cout << partnums[i] << " ";
partnums.push_back(157);
cout << "\n\nAfter adding an element to the end of the
list,"
<< "\n the vector has a size of " <<
int(partnums.size()) << ","
<< "and contains the elements:\n";
for (i = 0; i < int(partnums.size()); i++)
cout << partnums[i] << " ";
sort(partnums.begin(), partnums.end());
cout << "\n\nAfter sorting, the vector's elements are:
\n";
for (i = 0; i < int(partnums.size()); i++)
cout << partnums[i] << " ";
cout << endl;
return 0;
}
//C++ Program 7.14 as follows
#include<bits/stdc++.h>
using namespace std;
int main()
{
int num;
cout<<"Enter the number of elements in the array : ";
cin>>num;
int arr[num];
cout<<"Now enter "<<num<<" elements "<<endl;
for(int i=0;i<num;i++)
cin>>arr[i];
int i;
vector<int> partnums(arr, arr + num);
cout << "\nThe vector initially has the size of "
<< int(partnums.size()) << ",\n and contains the elements:\n";
for (i = 0; i < int(partnums.size()); i++)
cout << partnums[i] << " ";
partnums[3] = 144;
cout << "\n\nAfter replacing the fourth element, the vector has a size of "
<< int(partnums.size()) << ",\n and contains the elements:\n";
for (i = 0; i < int(partnums.size()); i++)
cout << partnums[i] << " ";
partnums.insert(partnums.begin()+1, 142);
cout << "\n\nAfter inserting an element into the second position, "
<< "\n the vector has a size of " << int(partnums.size()) << ","
<< "and contains the elements: \n";
for (i = 0; i < int(partnums.size()); i++)
cout << partnums[i] << " ";
partnums.push_back(157);
cout << "\n\nAfter adding an element to the end of the list,"
<< "\n the vector has a size of " << int(partnums.size()) << ","
<< "and contains the elements:\n";
for (i = 0; i < int(partnums.size()); i++)
cout << partnums[i] << " ";
sort(partnums.begin(), partnums.end());
cout << "\n\nAfter sorting, the vector's elements are: \n";
for (i = 0; i < int(partnums.size()); i++)
cout << partnums[i] << " ";
cout << endl;
return 0;
}