﻿ While Loop Example
```//---------------------------------------------------------
// Filename: CountLoop.cpp
//
// Purpose: Find the average of a list of values. The
// values are entered by the user.
//
// This program was written to illustrate a count controlled
// loop.
//
// D. Searls
// Asbury College
// Sep 2006
//---------------------------------------------------------
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
int numValues; // Number of values
int count;     // Number of values processed so far
double x;      // A single value from list
double sum;    // Sum of values
double avg;    // The arithmetic average

// Get number of scores

cout << "Enter the number of values in the list: ";
cin >> numValues;
cout << endl;

// Initialize sum and counter

sum = 0.0;
count = 0;

// Read scores, maintaining a running total and counter

while (count < numValues)
{
count = count + 1;
cout << "Enter score " << count << ": ";
cin >> x;
sum = sum + x;
}
cout << endl;

// Calculate average

if (numValues > 0)
{
avg = sum/(double)numValues;
}

// Display results

if (numValues > 0)
{
cout << "Number of scores read: " << numValues << endl;
cout << "Sum of scores: " << sum << endl;
cout << fixed << setprecision(2) ;
cout << "Average score: " << avg;
}
else
{
cout << "The list contained no scores.";
}
cout << endl << endl;
return 0;
}```
```//---------------------------------------------------------
// Filename: SentinelLoop.cpp
//
// Purpose: Find the average of a list of values. The
// values are entered by the user.
//
// This program was written to illustrate a sentinel
// controlled loop.
//
// D. Searls
// Asbury College
// Sep 2006
//---------------------------------------------------------
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
int numValues; // Number of values
double x;      // A single value from list
double sum;    // Sum of values
double avg;    // The arithmetic average

// Display instructions

cout << "Enter the values in the list. Enter a negative value when you are done.";
cout << endl << endl;

// Initialize sum and counter

sum = 0.0;
numValues = 0;

// Read scores, maintaining a running total and counter

cout << "Enter first score (negative to terminate): ";
cin >> x;
while (x >= 0)
{
numValues = numValues+1;
sum = sum + x;
cout << "Enter next score (negative to terminate): ";
cin >> x;
}
cout << endl;

// Calculate average

if (numValues > 0)
{
avg = sum/double(numValues);
}

// Display results

if (numValues > 0)
{
cout << "Number of scores read: " << numValues << endl;
cout << "Sum of scores: " << sum << endl;
cout << fixed << setprecision(2) ;
cout << "Average score: " << avg;
}
else
{
cout << "The list contained no scores.";
}
cout << endl << endl;
return 0;
}```