In: Computer Science
c++
We can dynamically resize vectors so that they may grow and shrink. While this is very
convenient, it is inefficient. It is best to know the number of elements that you need for your vector
when you create it. However, you might come across a situation someday where you do not know
the number of elements in advance and need to implement a dynamic vector.
Rewrite the following program so that the user can enter any number of purchases, instead of just
10 purchases. Output the total of all purchases. Hint: us do while loop with your vector..
#include
#include
using namespace std;
int main()
{
vector purchases(10);
for (int i = 0; i < 10; i++)
{
cout << "Enter a purchase amount";
cin >> purchases[i];
}
return (0);
}
Write your code here:
Use the Snipping Tool to show output
C++ program :-
#include
<iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> purchases;
int check = 1;
int temp;
while(check)
{
cout << "Enter a purchase amount:"<<endl;
cin >> temp;
purchases.push_back(temp);
cout<< "Wnat to add more...press 1 for yes and 0 to stop
:"<<endl;
cin>>check;
}
cout <<endl<< "Output : ";
for (auto i = purchases.begin(); i != purchases.end(); ++i)
cout << *i << " ";
return 0;
}
Output :-