This program finds the total of numbers that are 0 or more. This program would work for scores on a test for instance, where a negative value is not in the valid data. Entering a value less than 0 ends the loop. This value that ends the loop is called a sentinel value.

1 | // Find total, count, print average #include <iostream> using namespace std; int main() { int count=0, total=0, num; cout<<"Enter number: "; cin>>num; // read first number while (num>=0) { total+=num; count++; cout<<"Enter number (-1 to end): "; cin>>num; // read next number } // while cout<<"Total = "<<total<<"\n"; cout<<"Count = "<<count<<"\n"; if (count > 0) // avoid dividing by zero! cout<<"Average = "<<1.0*total/count<<"\n"; return 0; } // main |

- Run the program in your compiler. Trey different sets of numbers.
- Enter data that will cause the value of count to be 0.