In this chapter, you will study the important case of using loops to process large sets of data. You will often use a loop to go through a large amount of data to accumulate (aggregate) some intermediate result, which becomes the final result after the loop terminates.
Sum of the Entered Numbers
A typical task in this category is summing a lot of values.
Task
Say the user is entering numbers, with the last one being 0. In other words, users indicate they are finished by entering 0. The program then displays the sum of all the entered numbers (see Figure 24-1).
Figure 24-1 Summing all numbers until 0
Solution
The solution’s core is accumulating the intermediate result. You have to keep it in a variable and to add every entered number into that variable. As soon as the user terminates the input, the variable will contain the overall sum of all the entered values.
Here’s the code:
static void Main(string[] args)
{
// Preparations
int sum = 0;
int number;
// Entering numbers until zero
do
{
// Input
Console.Write("Enter a number (0 = end): ");
string input = Console.ReadLine();
number = Convert.ToInt32(input);
// Adding to intermediate sum
sum += number;
} while (number != 0);
// Output
Console.WriteLine("Sum of entered numbers is: " + sum.ToString());
// Waiting for Enter
Console.ReadLine();
}
Product of the Entered Numbers
What about multiplying the entered numbers instead of summing them? Do you think the task is the same? It’s not completely.
Task
In this program the user enters numbers, with the last one being 0 (see Figure 24-2). The program then displays the product of all the entered numbers, with the exclusion of the final 0, obviously, which would make everything 0.
Figure 24-2 Multiplying all numbers
Solution
Here’s the code:
static void Main(string[] args)
{
// Preparations
double product = 1;
int number;
// Entering numbers until zero
do
{
// Input
Console.Write("Enter a number (0 = end): ");
string input = Console.ReadLine();
number = Convert.ToInt32(input);
// Accumulating in intermediate product (but not the last zero!)
if (number != 0)
{
product *= number;
}
} while (number != 0);
// Output
Console.WriteLine("Product of entered numbers (excluding zero) is: " + product.ToString("N0"));
// Waiting for Enter
Console.ReadLine();
}
Discussion
Note the following:
The product variable starts at a value of 1 contrary to 0, which you used when calculating the sum.
When updating the product, you need to take care not to include the final 0.
You declare the product variable in type double for the result not to overflow. When you multiply, you quickly get big numbers.
The Greatest
Another typical task when processing a large amount of data is searching for the extremes, in other words, the maximum or the minimum.
Task
In this program, the user enters ten numbers. The program then outputs which one is the greatest (see Figure 24-3).
Figure 24-3 Outputting the greatest number
Solution
You are going to accumulate the intermediate result again. This time it will be the greatest number “so far.” You have to take special care with the first value; the greatest variable is set to the least possible value at the beginning in order to ascertain that the first entered number is always greater.
Because you expect exactly ten values in the input, it is more convenient to use the for loop here.
Here’s the code:
static void Main(string[] args)
{
// Preparation
int greatest = int.MinValue;
// Input of ten numbers
for (int order = 1; order <= 10; order++)
{
// Input
Console.Write("Enter " + order.ToString() + ". number: ");
string input = Console.ReadLine();
int number = Convert.ToInt32(input);
// Is it greater than the greatest so far?
if (number > greatest)
{
greatest = number;
}
}
// Output
Console.WriteLine("The greatest of entered numbers was: " + greatest.ToString());
// Waiting for Enter
Console.ReadLine();
}
The Second Greatest
What about the second greatest value? This is a substantially more difficult exercise.
Task
The task is to choose the second greatest number out of the ten entered ones (see Figure 24-4).
Figure 24-4 Displaying the second greatest number
Solution
You need to remember and continuously update the two greatest numbers greatest . It would not be enough to remember just the second greatest.
The situation resembles a ski competition, with the competitors arriving to the finish line one after another. At a certain moment, someone is the first. Afterward, someone else pushes the first out to the second place. Possibly in a later time, that skier may lose even the second place because someone else will be better than him, or even better than the new leader.
Here’s the code:
static void Main(string[] args)
{
// Preparation
int greatest = int.MinValue;
int secondGreatest = int.MinValue;
// Input of ten numbers
for (int order = 1; order <= 10; order++)
{
// Input
Console.Write("Enter " + order.ToString() + ". number: ");
string input = Console.ReadLine();
int number = Convert.ToInt32(input);
// Is it greater than the greatest so far?
if (number > greatest)
{
// Moving so far greatest to the second place
secondGreatest = greatest;
// Entered number becomes the greatest so far
greatest = number;
}
else
{
// We did not beat the greatest, will we beat the second greatest at least?
if (number > secondGreatest)
{
secondGreatest = number;
}
}
}
// Output
Console.WriteLine("The second greatest of entered numbers was: " + secondGreatest.ToString());
// Waiting for Enter
Console.ReadLine();
}
Output of All Entered Names
The final exercise of the chapter is concerned with text, specifically processing a large amount of text (see Figure 24-5).
Figure 24-5 Printing in the original order and then reversed
Task
You will write a program that repeatedly reads the names entered by the user. The empty input signals the termination. The program then repeats all the entered names, first in the same order and then in the reversed order
Solution
So that you are able to repeat all the names at the end, you need to remember them somewhere. You need to accumulate them. One variable will accumulate them at its end (the same order output) and the other one at its beginning (the reversed order output).
Here’s the code:
static void Main(string[] args)
{
// Preparation
string inSameOrder = "";
string inReversedOrder = "";
bool terminating;
// Repeating until blank input
do
{
// Input
Console.Write("Enter person: ");
string person = Console.ReadLine();
// Processing input
terminating = person.Trim() == "";
if (!terminating)
{
inSameOrder = inSameOrder + person + ", ";
inReversedOrder = person + ", " + inReversedOrder;
}
} while (!terminating);
// Removing trailing comma and space
if (inSameOrder.EndsWith(", "))
{
int numberOfCharacters = inSameOrder.Length;
inSameOrder = inSameOrder.Remove(numberOfCharacters - 2);
}
if (inReversedOrder.EndsWith(", "))
{
int numberOfCharacters = inReversedOrder.Length;
inReversedOrder = inReversedOrder.Remove(numberOfCharacters - 2);
}
// Output
Console.WriteLine("Entered persons: " + inSameOrder);
Console.WriteLine("In reversed order: " + inReversedOrder);
// Waiting for Enter
Console.ReadLine();
}
Discussion
Note the following:
You use the Trim method to cut off possible leading and trailing spaces of the entered text in order to allow termination with any blank input, including several spaces.
At the end, you have to get rid of the last two characters in both accumulated pieces of text. Before doing it, you test whether these two characters (a comma and a space) appear at the end of the text at all. These characters will not be there if the user immediately terminates the program by entering a blank line.
To test whether text ends with something, you use the EndsWith method.
Summary
One of the most frequent usages of loops is processing large amounts of data, be it numbers, text, or whole objects. In the loop’s body, you process a single piece of data, while the loop ascertains that all the data gets its turn.
You practiced processing larger amounts of data with examples of summing, multiplying, and finding extremes.
The most difficult exercise was that of finding the second greatest number, which required careful thinking about the possible situation that may arise depending on the data.
The last task showed you several methods to cope with text: Trim, EndsWith, and Remove.