ern8168
ern8168

Reputation: 3

Trying to end for loop

I am trying to create a loop that allows the user to enter as many elements to the array as they would like then sum up those elements. I need the loop to terminate when the user enters a negative number. How would I go about terminating this?

double sum = 0;
double group[] = { 0 };

for (int i = 0; i >= 0; i++) {

    cout << "Please enter employee salary. Enter negative number to end." << endl;
    cout << "Employee " << i + 1 << ": $";
    cin >> group[i];
    if (i < 0) {
        break;
    }
    sum += group[i];
}
cout << "The total salary ouput for Ernest Inc is: $" << fixed << showpoint << setprecision(2) << sum << endl;

Upvotes: 0

Views: 65

Answers (1)

tdao
tdao

Reputation: 17678

I need the loop to terminate when the user enters a negative number.

For that a while loop would be better than for. You should also use vector which allows arbitrary number of items.

Something like this:

    vector<double> group;
    double salary;
    while (true)
    {
        
        cout << "Please enter employee salary. Enter negative number to end." << endl;
        cout << "Employee " << i + 1 << ": $";
        cin >> salary;
        if (salary<0)
        {
            break;
        }
        group.push_back(salary);
        sum += salary;
    }

Upvotes: 1

Related Questions