//write a program whih takes input until user enters a negative number. print the sum of given inputs.
#include <iostream>
using namespace std;
int main ()


    {   int a[10];



    cout << " enter numbers " << endl ;
    int i = 0 ;
    while ( i < 10)
    {while (a[i] > 0 ) {cin>>a[i];}
    i++;}
    int sum = 0;
    i = 0 ;
    while ( i < 10  )
    {sum=sum+a[i];

    i++;}

    cout<< " sum is " <<sum;


   system ("pause");

   return 0 ;

}

Recommended Answers

All 2 Replies

what is problem in this code ?

With your current approach, you are actually making this far more difficult than it is.
There is no reason to use an array, all you need are two integer variables, one to hold the current input and the second to hold the sum.
Then you continue to take integer input and add it to the sum, until the integer entered is negative.
So thus far:

    int number = 0;
    int sum = 0;

    cout << "enter numbers:\n";
    while ((cin >> number) && (number >= 0))
    {
        sum += number;
    }

After that you need to flush the input stream, refer to this article for further information.
Just use cin.ignore(90, '\n'); for this program.
Then display the sum.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.