Week 6
6b) Write a C++ program that reads a series of numbers and stores them in a vector
Aim::To find the sum of first "n" numbers in vector
Program::
#include< iostream> #include< vector> using namespace std; int main() { vector< int>vector; int myint=1; int i,n,sum=0; cout<<"Please enter some numbers(enter 0 to stop) \n"; while(myint!=0) { cin >>myint; if(myint!=0) vector.push_back(myint); } cout<<"Enter how many numbers you wish to sum \n"; cin>>n; cout<<"The sum of first "<< n<< " numbers:"; for(i=0;i< n;i++) { sum+=vector[i]; cout<< vector[i] <<"\t"; } cout<< " is "<< sum; }
Output::
Please enter some numbers(enter 0 to stop) 12 23 13 24 15 0 Enter how many numbers you wish to sum 3 The sum of first 3 numbers:12 23 13 is 48
No comments:
Post a Comment