0

some one tell me that if we want to terminate this program on -1 then which condition we use..
please help...

#include <iostream.h>
#include <conio.h>
main()
{
      int arr[10],i,sum=0;
      for(i=0;i<10;i++)
      {
              cout<<"Enter values:";
      cin>>arr[i];
      sum=sum+arr[i];
      }
      cout<<"Sum is equal to="<<sum;


      getch();
      }
2
Contributors
1
Reply
7
Views
3 Years
Discussion Span
Last Post by deceptikon
0

Do you really want to terminate the program or just terminate the input process? The latter strikes me as more intuitive:

int main()
{
    int arr[0], i, sum = 0;

    cout << "Enter values: ";

    for (i = 0; i < 10; i++)
    {
        int input;

        if (!(cin >> input) || input == -1)
        {
            // Terminate input loop on -1 or input error
            break;
        }

        arr[i] = input;
        sum += arr[i];
    }

    if (i > 0)
    {
        // Only print the sum if a number was entered
        cout << "Sum is equal to " << sum << '\n';
    }

    getch();
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.