﻿ While Loop Example
```//---------------------------------------------------------
// Filename: FileLoop.cpp
//
// Purpose: Find the average of a list of values. The
// values are read from a file.
//
// D. Searls
// Asbury College
// Sep 2006
//---------------------------------------------------------
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;

int main()
{
string filename; // Name of input file
int numValues;   // Number of values
double x;        // A single value from list
double sum;      // Sum of values
double avg;      // The arithmetic average
ifstream infile; // The input file

// Get name of file

cout << "Enter the name of the data file (test.dat): ";
cin >> filename;
cout << endl << endl;

// Initialize sum and counter

sum = 0.0;
numValues = 0;

// Read scores, maintaining a running total and counter

infile.open(filename.c_str());
infile >> x;
while (!infile.fail())
{
numValues = numValues+1;
sum = sum + x;
infile >> x;
}
infile.close();

// 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;
}```
```//---------------------------------------------------------
// This program converts a numeral representing a non-
// negative integer to an integer type value. It also
// converts a non-negative integer value to a string
// representation (a numeral).
//
// D. Searls
// Asbury College
// Sep. 2006
//---------------------------------------------------------

#include <iostream>
#include <string>
using namespace std;

int main()
{
string numeral;
int integer;
char ch;
int digit;
int position;

cout << "Enter a non-negative integer value: ";
cin >> numeral;
cout << endl;

// Convert a numeral (a string) to an integer

integer = 0;
position = 0;
while(position < (int)numeral.length())
{
ch = numeral.at(position);
digit = int(ch) - int('0');
integer = 10 * integer + digit;
position = position + 1;
}

cout << "The integer is " << integer << endl;

// Convert an integer to a numeral (a string)

numeral = "";

digit = integer % 10;
integer = integer /10;
ch = char(int('0') + digit);
numeral = ch + numeral;
while (integer > 0)
{
digit = integer % 10;
integer = integer /10;
ch = char(int('0') + digit);
numeral = ch + numeral;
}

cout << "The numeral is \"" << numeral << '\"' << endl;

return 0;
}```