A simple adding machine.
Watch this video to learn about the new concepts shown in the program:
A “sentinel” is a dummy value that is used to terminate a while iteration. Most commonly used with Console.ReadLine() to mark the end of an input stream.
You have to be careful that the sentinel value is not valid data.
You can use true as a value to create an infinite loop. E.g. while (true) will never end because true is always true. This can be useful if you don’t want your program to end unless the user closes the program.
Questions to think about with this program to check your understanding:
Explain why the Console.ReadLine() call:
string data = Console.ReadLine();
must be inside the while (!complete) loop and not before it.
You want the user to be able to keep entering numbers until they enter the sentinel value, so the input must be inside the loop.
What is the problem with using zero as the sentinel value?
It means that zero can never be input as a valid number. This is a problem if you want the data set to include zeros for the purpose of calculating the average. A better approach (used here) is to read the input as a string first, check if it equals the sentinel character, and only then convert it to a double. The sentinel letter becomes the terminator and not the number zero.
Change the program so that it:
double.Hint
The lowest number will need to be initialised to be the first number that is input.
Enter number:
4
Enter number:
2
Enter number:
8
Enter number:
6
Enter number:
e
Total: 20.0 Top: 8.0 Bottom: 2.0 Ave: 5.0
// Adder program
using System;
class Submission
{
---
// -------------------------
// Subprograms
// -------------------------
// A simple adding machine
static void adder()
{
---
double total = 0; // Total
double top = 0; // Highest number
double bottom = 0; // Lowest number
int count = 0; // Count of numbers
double ave = 0; // Average
bool complete = false;
---
// Repeat until sentinel value entered 'e'
while (!complete)
{
---
Console.WriteLine("Enter number:");
string data = Console.ReadLine();
---
// Add the number if it is not the sentinel
if (data != "e")
{
---
double number = Convert.ToDouble(data);
total = total + number;
count = count + 1;
---
// Set the highest number
if (number > top)
{
---
top = number;
---
}
---
// Set the lowest number
if ((count == 1) || (number < bottom))
{
---
bottom = number;
---
}
---
}
---
else {
complete = true;
// Prevent a division by zero error
if (count > 0)
{
---
ave = total / count;
---
}
---
else
{
---
ave = 0;
---
}
---
}
---
}
---
Console.WriteLine($"Total: {total} Top: {top} Bottom: {bottom} Ave: {ave}");
---
}
---
// -------------------------
// Main program
// -------------------------
public static void Main(string[] args)
{
---
adder();
---
}
---
}