In: Computer Science
Write a C++ program that continuously requests a donation to be entered. If the donation is less than 0 or greater than 10, your program should print an appropriate message informing the user that an invalid donation has been entered, else the donation should be added to a total. When a donation of -1 is entered, the program should exit the repetition loop and compute and display the average of the valid donations entered.
Here we used a while loop and controls like continue and break for calculating average valid donation.
Commented code to explain it's working is below:
#include <iostream>
using namespace std;
int main()
{
    // count total of valid donations made
    int total = 0;
    // count no of valid donations mase
    int n = 0;
    // Looop to keep asking user
    while(1){
        // to store user input to
        int donation; 
        cout<<"Enter the donation amount: ";
        cin>>donation;
        // stop loop if -1 is entered
        if(donation == -1)
            break;
        if(donation<0 || donation >10){
            cout<<"Invalid amount entered."<<endl;
            // Looop again by discarding current donation value
            continue;
        }
        total+=donation;
        n++;
    }
    // calulate average of valid donations
    float avg = (float)total/n;
    cout<<"Average: "<<avg<<endl;
    return 0;
}
Output:
