MENU











Wednesday, 16 October 2013

Week 6 programs

Week 6

6b) Write a C++ program that reads a series of numbers and stores them in a vector. After the user inputs all the numbers he wishes to, ask how many of the numbers the user wants to sum. For an answer N, print the sum of the first N elements of the vector. For example “Please enter some numbers (press "0" at prompt to stop):” 12 23 13 24 15 “Please enter how many of the numbers you wish to sum, starting from the first:” 3 “The sum of the first 3 numbers : 12 23 and 13 is 48”

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