Staying with the topic of conditions, you will now proceed to more complex examples. In this chapter, you will meet tasks that can be solved using several conditions in a single program.
Soccer
First, you will consider in detail a typical situation of three branches of alternative execution paths.
Task
You will prepare a program in which the user enters data about a soccer match: the numbers of goals scored by both sides. The program then evaluates the match result. It displays whether the first club won , the second club won, or it was a tie (see Figures 18-1, 18-2, 18-3).
Figure 18-1 The first club won
Figure 18-2 It’s a tie
Figure 18-3 The second club won
Analysis
You can solve the task using three conditions in a row, each of them considering a specific match result (see Figure 18-4).
Figure 18-4 The program flow
Solution
Here is the code:
static void Main(string[] args)
{
// Inputs
Console.Write("Goals scored by Liverpool: ");
string inputLiverpool = Console.ReadLine();
int goalsLiverpool = Convert.ToInt32(inputLiverpool);
Console.Write("Goals scored by Manchester: ");
string inputManchester = Console.ReadLine();
int goalsManchester = Convert.ToInt32(inputManchester);
// Evaluating
if (goalsLiverpool > goalsManchester)
{
Console.WriteLine("Liverpool won.");
}
if (goalsLiverpool == goalsManchester)
{
Console.WriteLine("Tie.");
}
if (goalsLiverpool < goalsManchester)
{
Console.WriteLine("Manchester won.");
}
// Waiting for Enter
Console.ReadLine();
}
Soccer Alternatively
To show you another point of view, you will solve the previous exercise in an alternative way. Previously you used three conditions in a row. This time you will nest the second condition into the first one.
Analysis
As shown in Figure 18-5, the program will branch into the following alternatives first:
Liverpool won.
Liverpool did not win.
The alternative, “Liverpool did not win,” will be further branched into the following:
Tie.
Manchester won.
Figure 18-5 The program flow
Solution
Here is the code:
static void Main(string[] args)
{
// Inputs
Console.Write("Goals scored by Liverpool: ");
string inputLiverpool = Console.ReadLine();
int goalsLiverpool = Convert.ToInt32(inputLiverpool);
Console.Write("Goals scored by Manchester: ");
string inputManchester = Console.ReadLine();
int goalsManchester = Convert.ToInt32(inputManchester);
// Evaluating
if (goalsLiverpool > goalsManchester)
{
// Here we know Liverpool won. We can display the result.
Console.WriteLine("Liverpool won.");
}
else
{
// Here we know Liverpool did not win. We will decide
// between tie and victorious Manchester
if (goalsLiverpool == goalsManchester)
{
Console.WriteLine("Tie.");
}
else
{
Console.WriteLine("Manchester won.");
}
}
// Waiting for Enter
Console.ReadLine();
}
Minimum of Three Numbers
The next example uses conditional execution to compare three numbers.
Task
You will write a program that finds the smallest of three numbers entered by the user (see Figure 18-6).
Figure 18-6 Finding the smallest number
Analysis
The task can be solved by subsequent processing of all the entered numbers. You will use a helper variable to store the minimal value found so far.
At the beginning, the first entered number becomes the minimum. In the second step, you compare the second number to the minimum. If the former is less than the latter, the former becomes the minimum. Finally, the same procedure is performed with the third number.
Solution
Here is the code:
static void Main(string[] args)
{
// Inputs
Console.Write("Enter 1. number: ");
string input1 = Console.ReadLine();
int number1 = Convert.ToInt32(input1);
Console.Write("Enter 2. number: ");
string input2 = Console.ReadLine();
int number2 = Convert.ToInt32(input2);
Console.Write("Enter 3. number: ");
string input3 = Console.ReadLine();
int number3 = Convert.ToInt32(input3);
// At the beginning, we set 1st number as minimum
int minimum = number1;
// Is not 2nd number less than present minimum?
if (number2 < minimum)
{
minimum = number2;
}
// Is not 3rd number less than present minimum?
if (number3 < minimum)
{
minimum = number3;
}
// Output
Console.WriteLine("The least of entered numbers is " + minimum);
// Waiting for Enter
Console.ReadLine();
}
Minimum with Built-in Function
You can solve the previous exercise using the Math.Min function, which is readily available in C#. The function itself determines the least of two numbers. I will show you how to use it for the case of three numbers.
Solution
First you determine the smallest of the first and second numbers. The result will then “compete” with the third one.
Here is the code:
static void Main(string[] args)
{
// Inputs
Console.Write("Enter 1. number: ");
string input1 = Console.ReadLine();
int number1 = Convert.ToInt32(input1);
Console.Write("Enter 2. number: ");
string input2 = Console.ReadLine();
int number2 = Convert.ToInt32(input2);
Console.Write("Enter 3. number: ");
string input3 = Console.ReadLine();
int number3 = Convert.ToInt32(input3);
// Evaluating
int min12 = Math.Min(number1, number2);
int minimum = Math.Min(min12, number3);
// Output
Console.WriteLine("The least of entered numbers is " + minimum);
// Waiting for Enter
Console.ReadLine();
}
Linear Equation
This exercise will get a bit into mathematics.
Task
You will write a program to solve a linear equation, in other words, an equation of the type ax + b = 0.
For example, 2x + 6 = 0 is a linear equation, with the 2 being a and the 6 being b.
The solution is clearly -3. When you substitute -3 for x, the left side becomes zero, in other words, equal to the right side.
The user enters the equation to be solved in the form of the coefficients a and b. The program then calculates and displays its solution (see Figure 18-7).
Figure 18-7 Calculating and displaying its solution
Analysis
Whenever you want to program anything, you need to understand the real-world problem first. In other words, you need to know how to solve it without a computer.
What follows is a mathematical reminder of how to solve a linear equation:
If a is not zero, the obvious solution is -b/a.
The case of a equal to zero is a kind of mathematical curiosity. The equation degenerates to a strange “equation without x” or the pseudo-equation b = 0. Such an “equation”
Has infinitely many solutions for b equal to zero (it always holds regardless of x)
Does not have a solution for a nonzero b (no x can fulfill the equation)
Solution
Here is the code:
static void Main(string[] args)
{
// Inputs
Console.Write("Enter a: ");
string inputA = Console.ReadLine();
double a = Convert.ToDouble(inputA);
Console.Write("Enter b: ");
string inputB = Console.ReadLine();
double b = Convert.ToDouble(inputB);
// Solving the equation
if (a != 0)
{
// a is non-zero, the equation has "normal" solution
double solution = -b / a;
Console.WriteLine("Solution is x=" + solution);
}
else
{
// a is zero, result depends on b
if (b == 0)
{
Console.WriteLine("The equation "is solved" by any x");
}
else
{
Console.WriteLine("The equation does not have a solution");
}
}
// Waiting for Enter
Console.ReadLine();
}
Quadratic Equation
Staying with mathematics, the next exercise concerns a more difficult quadratic equation.
Task
You will write a program to solve a quadratic equation, in other words, an equation like ax 2 + bx + c = 0. An example of a quadratic equation is x 2 – x - 2 = 0 with a being 1, b being -1, and c being -2. The equation mentioned has two solutions: -1 and 2. Substituting any of the two zeros the left side.
The equation to be solved will be entered in the form of the coefficients a, b, and c. The program calculates and displays its solution (see Figure 18-8).
Figure 18-8 Solving a quadratic equation
For the sake of simplicity, you will not consider the case of a equal to zero, which would transfer the task to the previous one, a linear equation.
Analysis
Once upon a time, someone clever worked out a procedure to solve quadratic equations. You probably know it from school. You calculate the so-called discriminant first.
The solution then branches according to the discriminant value.
For D > 0, the equation has two solutions given by the following:
For D = 0, the same formula applies with the two solutions coinciding.
For D < 0, the equation does not have a solution in real numbers.
Solution
Here is the code:
static void Main(string[] args)
{
// Inputs
Console.Write("Enter a: ");
string input = Console.ReadLine();
double a = Convert.ToDouble(input);
Console.Write("Enter b: ");
string inputB = Console.ReadLine();
double b = Convert.ToDouble(inputB);
Console.Write("Enter c: ");
string inputC = Console.ReadLine();
double c = Convert.ToDouble(inputC);
// Solving + output
double d = b * b - 4 * a * c;
if (d > 0)
{
double x1 = (-b - Math.Sqrt(d)) / (2 * a);
double x2 = (-b + Math.Sqrt(d)) / (2 * a);
Console.WriteLine("The equation has two solutions:");
Console.WriteLine(x1);
Console.WriteLine(x2);
}
if (d == 0)
{
double x = -b / (2 * a);
Console.WriteLine("The equation has a single solution: " + x);
}
if (d < 0)
{
Console.WriteLine("The equation does not have a solution");
}
// Waiting for Enter
Console.ReadLine();
}
Discussion
The most interesting point of this exercise is the way you enter the formula in code. Note that the numerator and the denominator have to be enclosed in parentheses to ascertain the correct order of calculations! The mathematical formula does not contain them because mathematicians use fractions.
When calculating the discriminant, I do not use parentheses; I just rely on the precedence of multiplication to subtraction.
Test
To check that the program calculates correctly, you can write further code as a test; the left side should become zero after substituting the solution for x.
Summary
In this chapter, you saw several examples of using more than one condition to do the task assigned.
First, you solved a soccer match evaluation in two alternative ways. The first one considered the individual possibilities one after another using three simple if statements. The second one used a branch nested inside another branch.
You further exercised multiple conditions in a row one after another to find the smallest of three numbers. To do this, you stored a “minimum-so-far” value in a helper variable.
The same task was then solved using the built-in function Math.Min. You already know that the function determines the minimum of two values. Here I showed you an interesting case of how you can use it for three numbers.
In the final two tasks, you practiced multiple conditions in examples from mathematics, namely, solving linear and quadratic equations. The last task gave you the opportunity to see a bit more complex calculation written in code.