© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2022
G. ByrneTarget C#https://doi.org/10.1007/978-1-4842-8619-7_8

8. Arithmetic

Gerard Byrne1  
(1)
Belfast, Ireland
 

Arithmetic Operations

We learned in Chapter 7 that variables can be “converted” from one numeric data type to another, which is referred to as casting, or from a string value to a numeric value, which is called parsing. Parsing uses methods from a wrapper class to convert the string data to a numeric data type value. These are important concepts and widely used in all programming languages by professional developers. As we develop our C# skills throughout the chapters, we will use these concepts, so it is worthwhile constantly reminding ourselves of the differences between casting and parsing and how they are used within C# code.

Arithmetic in Our Business Logic

The code, or business logic as it is often called, of many applications will have some degree of computation or calculation. In C# it is possible to perform operations on integers and other numerical data types, in the same way we can perform operations in normal mathematics.

We will probably be aware from our mathematics lessons at school that mathematical operations are performed in a specific order, and therefore we need to ensure that formulae are written in such a way that the mathematical operators work in the correct order. Based on this knowledge, we should recognize that calculations that involve combinations of mathematical operators such as add (+), subtract (–), multiply (*), and divide (/) can return a different value when the order is changed. The normal algebraic rules of precedence or priority apply in any programming language, including C#, and need to be thoroughly understood and applied. The precedence can be understood using the acronym BODMAS , which means
  • Brackets

  • pOwers

  • Division (division and multiplication have the same priority)

  • Multiplication

  • Addition (addition and subtraction have the same priority)

  • Subtraction

Another widely used acronym instead of BODMAS is PEMDAS , which means
  • Parentheses

  • Exponents

  • Multiplication

  • Division (division and multiplication have the same priority)

  • Addition (addition and subtraction have the same priority)

  • Subtraction

To try and remember this acronym, people will use the mnemonic Please Excuse My Dear Aunt Sally, or another favorite is Please End My Day At School. Either acronym can be used and they mean the same thing.

As stated earlier it is vitally important that we get the correct answers when we execute calculations in our code. Therefore, we need to ensure that mathematical formulae are written correctly in our code. Big problems can be caused by, and for, developers when they code their formulae incorrectly. Often the coding errors in mathematical formulae are caused because developers misuse or do not use brackets ( ) to group expressions within their formulae.

Example 1
  • 6 * 5 3

  • We could take this to mean (which is the correct interpretation based on the rules)

  • 6 * 5 – This part is equal to 30.

  • 30 – 3 – This part is equal to 27.

  • If this was the intention, it should be written in a more clearly readable form as

  • (6 * 5) – 3

  • Now the brackets make it clear that 6 is multiplied by 5 and the answer will have 3 subtracted from it to give an answer of 27.

Alternatively, we could take it to mean
  • 5 – 3 – This part is equal to 2.

  • 6 * 2 – This part is equal to 12.

  • If this was the intention, it should be written in a more clearly readable form as

  • 6 * (5 3)

  • Now the brackets make it clear that 3 is subtracted from 5 and the answer is multiplied by 6 to give an answer of 12.

Example 2
  • 2 + 4 × 3 – 1 Multiply 4 by 3.

  • 2 + 12 – 1 Add 2 and 12.

  • 14 – 1 Subtract 1 from 14.

  • 13

  • If we use brackets, it can make the visualization of the actual order much easier:

  • 2 + 4 × 3 – 1 can be written as 2 + (4 x 3) – 1.

Without brackets it can be harder to see what needs to be done in the formula. By using brackets ( ) to group expressions within the formula, we can make it much easier to understand. This idea of making code easier to read forms part of the concept of clean code. When we have clean code , we are more likely to have code that is easier to read and maintain.

Common Arithmetic Operators

Within C# we have access to a number of arithmetic operators, including those shown in the following, which we will use in this chapter and in many programs that we write:
  • Add +

  • Subtract -

  • Multiply *

  • Divide /

  • Modulus % the remainder

Integer Division

Integer division in any programming language, just as in mathematics, is an interesting operation in that we get an answer with a remainder, even if the remainder is 0. In programming, when two integer values are divided using the / operator, the result will be the whole part of the division and the remainder is not considered.

Example

  • 19/5 will give an answer of 3.

As we can see this is the whole number part and there is no indication of the remainder. Where has the remainder of 4 gone? It has effectively been lost as we have not used the division operator in its full format. We need to use the division operator alongside the modulus operator (%) . The modulus operator % gives the remainder after the division has been performed.

Example
  • 19%5 will give an answer of 4.

Console.WriteLine("19 / 5 will give an answer of " + (19 / 5));
Console.WriteLine("19 % 5 will give an answer of " + (19 % 5));
Console.WriteLine("19 divided by 5 will give an answer of "
        + (19 / 5) + " remainder " + (19 % 5));
Listing 8-1

Example code for division and modulus

Therefore, to do a division properly, we need to combine the division and the modulus parts as shown in the last WriteLine() statement in Listing 8-1.

Now it is time for us to do some C# coding where the console application we code will use mathematical operators to perform arithmetic. We will read data input from the console using the Console.ReadLine() method and will write to the console using the Console.WriteLine() method . As we are dealing with mathematical operators, our data will need to be numerical, so our code will apply some conversion using the Convert class and the appropriate methods of this class, for example, ToInt32(). We will also apply some casting, particularly when undertaking division, which involves int data types.

In creating this C# application, we should use the same solution that we created for the earlier chapters, as we will still be able to see the code we have written for the previous chapters. The approach of keeping all our separate projects in one solution is a good idea while studying this book and coding the examples. Having already created some projects, we should be getting familiar with the process of project creation, and the whole idea of following a standard process to create the projects helps us reinforce our learning.

Add a new project to hold the code for this chapter.
  1. 1.

    Right-click the solution CoreCSharp.

     
  2. 2.

    Choose Add.

     
  3. 3.

    Choose New Project, as shown in Figure 8-1.

     

A console window has a pop-up menu with options for new project, existing project and existing website. New project is highlighted. This opens another pop-up menu from which the add option is selected.

Figure 8-1

Adding a new C# project

  1. 4.

    Choose Console App from the listed templates that appear, as shown in Figure 8-2.

     

A console app window includes the following buttons, C hash, Linux, mac O S, Windows, and Console.

Figure 8-2

Selecting a new C# console project

  1. 5.

    Click the Next button.

     
  2. 6.

    Name the project Chapter8 and leave it in the same location, as shown in Figure 8-3.

     

A dialog box is titled console app. It consists of a box labelled project name, wherein chapter 8 is entered. Below it is a dropdown menu for location. The next button present at the bottom right is selected.

Figure 8-3

Naming a new C# console project

  1. 7.

    Click the Next button.

     
  2. 8.

    Choose the framework to be used, which in our projects will be .NET 6.0 or higher, as shown in Figure 8-4.

     

A dropdown menu for framework from which the option dot NET 6.0 long-term support is selected.

Figure 8-4

Choosing the project framework

  1. 9.

    Click the Create button.

     
Figure 8-5 shows the Chapter8 project within the solution called CoreCSharp .

A solution explorer panel has a folder named solution, single quote, core C sharp, single quote. Under it, chapter 8 is highlighted.

Figure 8-5

Solution Explorer displaying all projects

  1. 10.

    Right-click the Chapter8 project in the Solution Explorer panel.

     
  2. 11.

    Click the Set as Startup Project option.

     
Notice how the Chapter8 project name has been made to have bold text, as shown in Figure 8-6. This indicates that Chapter8 is the new startup project and it is the Program.cs file within it that will be executed when we debug.

A window has a folder named solution, single quote, core C sharp, single quote. Under it, chapter 8 is in bold font and is highlighted.

Figure 8-6

Solution Explorer displaying the startup project

Solution Explorer and Project Analysis

The CoreCSharp solution shown in Figure 8-7 represents the folder that the Visual Studio Integrated Development Environment uses to hold details about the solution and the projects managed by it.

A solution explorer window has a folder named solution, single quote, core C sharp, single quote, open parenthesis, 5 of 5 projects, close parenthesis.

Figure 8-7

Solution Explorer and its toolbar

Inside the folder is a file called CoreCSharp, which is the solution file. If we look in the Windows File Explorer or the Finder on a Mac computer, where our projects are held, we will notice that the file type is sln, which represents a Visual Studio solution.
  1. 12.

    Right-click the solution name.

     
  2. 13.

    Choose Open Folder in File Explorer, or Finder on a Mac, as shown in Figure 8-8.

     

A file explorer window is titled solution single quote, core C sharp, single quote. Under it, the option to open folder in file explorer is selected.

Figure 8-8

Right-clicking the solution and opening the folder in the File Explorer window

When the window opens, the CoreCSharp folder with the solution file will be displayed as shown in Figure 8-9.

A window has two columns with headers: name and type. The entry with the name core C sharp dot sin of type visual studio solution is boxed.

Figure 8-9

Solution file within a File Explorer window

The solution file holds information about the projects that are part of the overall solution. There is no need for us to ever amend this file. If we were to open the file in a text editor, we would see our solution has several projects, and this information is stored in the solution file as shown in Figure 8-10.

An information list stored in a solution file has 3 columns and 5 rows. The first column entries listing the chapters are boxed.

Figure 8-10

Solution file holding project information

  1. 14.

    Open the Chapter8 folder in File Explorer, or Finder on a Mac.

     

A file explorer window has 3 columns with headers: name, type, and size. A file named chapter 8 of type C S PROJ in capitals and size 1 K B is highlighted and selected.

Figure 8-11

Project file within a File Explorer window

Looking inside the Chapter8, or any other project, folder reveals the file that holds information about this project. In this project the file is called Chapter8 and has a type of csproj, a visual C# project file, as shown in Figure 8-11.

Amend the name of the Program.cs file .

In each of the chapters so far, we have created a project within the solution, and we have accepted that Visual Studio creates a Program.cs file by default, which we have unassumingly used as a template, and added our own C# code to it. But might we want to have a different name from Program.cs? Well, we might, but if this is the file that contains the Main() method, the main entry point to our application, it would be unusual to rename it. Convention would be to have a Program.cs file with the Main() method contained within it. Future chapters will have multiple files within our project, and we will want to give them all meaningful names so we can quickly understand what their purpose is. So let us now rename the Program.cs file in our Chapter8 project, and then we will be able to use the same principle throughout the rest of the book chapters, so we have names that associate our code with the example application we are coding.
  1. 15.

    Double-click the Chapter8 Program.cs file in the Solution Explorer window to open it in the editor window.

     
  2. 16.

    Right-click the Chapter8 Program.cs file in the Solution Explorer window.

     
  3. 17.

    Choose Rename.

     
  4. 18.

    Change the name to Arithmetic.cs.

     
  5. 19.

    Press the Enter key.

     
Code Analysis
  • If we have not switched off the top-level statements, as discussed in Chapters 4, 5, and 6, the new template in Visual Studio 2022, for a console application, is shown in the editor window.

  • So the Visual Studio Integrated Development Environment is great at helping, but the unnecessary using statements it gives us do not fit well with the clean code concept. There is a programming concept known as YAGNI, which stands for You Ain't Going To Need It, and having the lines of code from the template code fits into this, so we will remove these two lines of code:

// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");
We should now be getting a better understanding of the structure for projects and solutions and, as we learn more, we will see how to add different classes to our projects, with only one class in each project containing the Main() method. Obviously, we will need to have different names for each class in a project, so do we always want to have the Program.cs file, or would we like to rename it? Well, it is possible for us to rename the file, so we will, for reinforcement purposes only, change the name of our Arithmetic.cs file in this project within the Solution Explorer.
  1. 20.

    Right-click the Arithmetic.cs file in the Solution Explorer window.

     
  2. 21.

    Choose Rename.

     
  3. 22.

    Change the name to QuoteArithmetic.cs, as shown in Figure 8-12.

     
  4. 23.

    Press the Enter key.

     

A solution explorer window has a folder named chapter 8. Below it, the entry quote arithmetic dot c s is highlighted and is labeled renamed file.

Figure 8-12

Program.cs file renamed

First, we will set up the code structure for the file, which will be the entry point for our application. This will be the same structure for most of our projects:
  • First is a namespace.

  • Inside the namespace will be a class – here it is QuoteArithmetic.

  • Inside the class will be the Main() method.

The shortcut for creating the Main() method is to type svm and press the Tab key twice.
  1. 24.

    In the QuoteArithmetic editor window, add the code in Listing 8-2.

     
namespace Chapter8
{
  public class QuoteArithmetic
  {
    static void Main(string[] args)
    {
    } // End of Main() method
  } // End of QuoteArithmetic class
} // End of Chapter8 namespace
Listing 8-2

QuoteArithmetic.cs structure with class and namespace

Now we will add the variables to be used in our code. In the code in Listings 8-2 and 8-3 and future listings, there are detailed comments to help us get a full understanding of the code. In this example all code is contained within the opening and closing curly braces, { }, of the Main() method.
  1. 25.

    In the editor window, add the variables as shown in Listing 8-3.

     
namespace Chapter8
{
  public class QuoteArithmetic
  {
    static void Main(string[] args)
    {
      /*
      We will setup our variables that will be used in the
      mathematical calculation used to produce an insurance
      quotation for a vehicle.
      First we will setup the variables that will hold the user
      input and that will be used in calculating the quote
      */
      int vehicleAgeInYears;
      int vehicleCurrentMileage;
      /*
      For the quotation we will use 10000 kilometres as a base
      line for calculating a mileage factor. If the average
      kilometres travelled per year is above the base mileage of
      10000 the mileage factor will be above 1, if the average
      kilometres travelled per year is the lower than the base
      mileage of 10000 the mileage factor will be below 1
      */
      double quoteAverageExpectedKilometres = 10000;
      /*
      For the quotation we will use £100 as a base figure
      (this is just an example) and this figure will be
      multiplied by the mileage and age factors
      */
      double quoteBaseRate = 100.00;
      /*
      For the quotation we will use 10 as a base figure for the
      age of the vehicle (this is just an example).
      If the vehicle is older than 10 years, the age factor
      will be above 1.
      If the vehicle is younger than 10 years the age factor
      will be below 1
      */
      int quoteBaseAge = 10;
      /*
      This variable will be used to hold the value of the
      age factor
      */
      double quoteAgeFactor;
      /*
      This variable holds the quote amount based on the age
      factor and the base rate
      */
      double quoteAgeFactorPremium;
      /*
      This variable holds the quote mileage factor based on the
      number of kilometres travelled each year and how the
      kilometres per year is a ratio of the average expected
      10000 kilometres as decided by the insurance company
      */
      double quoteMileageFactor;
      /*
      This variable holds the amount for the quote based only
      on the mileage factor. The quote also has to take into
      account the age of the vehicle
      */
      double quoteMileageFactorPremium;
      /*
      This variable will hold the discount amount.
      A discount will be applied to the quote based on the age
      of the vehicle. The age of the vehicle is divided into 1
      to get the discount. The decimal value is a representation
      of the discount and will then be multiplied by the quote
      value to get the actual discount in terms of £s
      */
      double quoteDiscount;
      /*
      This variable holds the total of the age factor premium
      and the mileage factor premium and will be used by the
      discount calculation to get the discount amount
      */
      double quoteAmountForPremium;
      /*
      This variable holds the final quotation value, the premium.
      */
      double quoteFinalAmountForPremium;
    } // End of Main() method
  } // End of QuoteArithmetic class
} // End of Chapter8 namespace
Listing 8-3

Declaring the variables in the Main() method

Now we will write some information to the console and ask for user input.
  1. 26.

    Amend the code, as in Listing 8-4, adding print lines to the end of the code.

     
    /*
    This variable holds the final quotation value, the premium.
    */
    double quoteFinalAmountForPremium;
    Console.WriteLine();
    Console.WriteLine("---- Car Quotation Application ----");
    Console.WriteLine();
    Console.WriteLine("What is the age, in full years, of " +
        "the vehicle? ");
    } // End of Main() method
  } // End of QuoteArithmetic class
} // End of Chapter8 namespace
Listing 8-4

Displaying a message to the user

Now we will

  • Read the vehicle age input from the console and convert it to an int.

  • Use the vehicle age to calculate an age factor, by dividing the base age that we set up as one of the variables by the vehicle age.

  • Calculate the premium, based on the age factor and quote base rate of £100.

  1. 27.

    Amend the code, as in Listing 8-5, adding the lines to the end of the code.

     
      Console.WriteLine("What is the age, in full years, of " +
        "the vehicle? ");
      /*
      Perform the conversion, Parse, from string to int as we
      will use the age of the vehicle in our calculation and
      it needs to be numeric
      */
      vehicleAgeInYears = Convert.ToInt32(Console.ReadLine());
      /*
      Perform the conversion from string to int as we will use
      the age of the vehicle in our calculation and it needs
      to be numeric
      Example: For a 5 year old car the factor is 10/5 = 2
      */
      quoteAgeFactor = (double)(quoteBaseAge) /
        (double)(vehicleAgeInYears);
      /*
      The quote amount based on the age is £100 multiplied by
      the age factor
      Example £100 * 2 = £200
      */
      quoteAgeFactorPremium = quoteBaseRate * quoteAgeFactor;
    } // End of Main() method
  } // End of QuoteArithmetic class
} // End of Chapter8 namespace
Listing 8-5

Get user input for the vehicle age and perform calculations

Now we will

  • Read the vehicle mileage input from the console and convert it to an int.

  • Use the vehicle mileage and divide it by the age of the vehicle to get the average yearly mileage.

  • Divide this value by 10000, which is the expected yearly mileage, to calculate a mileage factor.

  • Calculate the premium based on the mileage factor and the quote base rate of £100.

  1. 28.

    Amend the code, as in Listing 8-6, to get the input and perform the two calculations.

     
      quoteAgeFactorPremium = quoteBaseRate * quoteAgeFactor;
      /*
      Ask the user for the number of kilometres on the odometer
      */
      Console.WriteLine("What is the current mileage (in km) " +
        "of the vehicle? ");
      vehicleCurrentMileage= Convert.ToInt32(Console.ReadLine());
      /*
      Calculate the mileage factor. This is based on the number
      of kilometres travelled each year and how the kilometres
      per year is a ratio of the average expected 10000
      kilometres as decided by the insurance company
      Example: For a 5 year old car with 60000km the factor is
                      (60000/5)/10000 = 12000/10000 = 1.2
      */
      quoteMileageFactor = (vehicleCurrentMileage /
        vehicleAgeInYears) / quoteAverageExpectedKilometres;
      /*
      The quote amount based on the mileage is £100
      multiplied by the mileage factor
      Example £100 * 1.2 = £120
      */
      quoteMileageFactorPremium = quoteBaseRate *
        quoteMileageFactor;
    } // End of Main() method
  } // End of QuoteArithmetic class
} // End of Chapter8 namespace
Listing 8-6

Get user input for the mileage and perform calculations

Now we will add the two values we have just calculated to give us the quote amount, the premium.
  1. 29.

    Amend the code , as in Listing 8-7, to calculate the quote amount.

     
      quoteMileageFactorPremium = quoteBaseRate *
        quoteMileageFactor;
      /*
      Calculate the quotation based on a base rate of £100.
      This base rate is multiplied by the vehicle age factor
      and by the vehicle mileage factor.
      So, the older the vehicle the cheaper the quote or the
      newer the vehicle the more expensive the quote.
      The more kilometres travelled on average per year the
      more expensive the quote or the less kilometres travelled
      on average per year the cheaper the quote.
      Example: For a 5 year old car, 60000km, age factor is 2
      and mileage factor is 1.2
      The quote is (£100*2) + (£100*1.2 )= £200 + £120 = £320
      */
      /*
      The quote amount based on the age premium plus the
      mileage premium
      Example £2000 + £120 = £320
      */
      quoteAmountForPremium = quoteAgeFactorPremium +
        quoteMileageFactorPremium;
    } // End of Main() method
  } // End of QuoteArithmetic class
} // End of Chapter8 namespace
Listing 8-7

Calculate the quote amount for the premium

Now we will calculate the discount based on the calculated premium and the vehicle age.
  1. 30.

    Amend the code, adding a quote discount formula to the end of the code, as in Listing 8-8.

     
      quoteAmountForPremium = quoteAgeFactorPremium +
        quoteMileageFactorPremium;
      /*
      The discount amount is based on the age of the vehicle
      Example:
      5 year old vehicle gives discount of 1/5 = 20 percent */
      quoteDiscount = (1 / (double)vehicleAgeInYears) *
        quoteAmountForPremium;
    } // End of Main() method
  } // End of QuoteArithmetic class
} // End of Chapter8 namespace
Listing 8-8

Calculate the quote discount and use casting

Now we will calculate the quote amount after the discount is applied.
  1. 31.

    Amend the code, as in Listing 8-9, to perform the calculation for the final premium amount.

     
      quoteDiscount = (1 / (double)vehicleAgeInYears) *
        quoteAmountForPremium;
      /*
      The final quote with the discount applied
      Example
      5 year old vehicle gives discount of 100/5 = 20 percent
      20% of £320 is £64.
      So, the actual amount is £320 - £64 = £256
      */
      quoteFinalAmountForPremium = quoteAmountForPremium -
        quoteDiscount;
    } // End of Main() method
  } // End of QuoteArithmetic class
} // End of Chapter8 namespace
Listing 8-9

Calculate the quote final amount

  1. 32.

    Amend the code, as in Listing 8-10, to add some print lines displaying a quotation.

     
       quoteFinalAmountForPremium = quoteAmountForPremium -
        quoteDiscount;
      Console.WriteLine("********************************** ");
      Console.WriteLine("Quotation is for 1 year from today ");
      Console.WriteLine("********************************** ");
      Console.WriteLine("The age of the vehicle is : " +
        vehicleAgeInYears);
      Console.WriteLine("The age factor is for this vehicle " +
        "is : " + quoteAgeFactor);
      Console.WriteLine();
      Console.WriteLine("The average kilometres per year " +
        "is : " + (vehicleCurrentMileage / vehicleAgeInYears));
      Console.WriteLine("The mileage factor is : " +
        quoteMileageFactor);
      Console.WriteLine();
      Console.WriteLine("The quotation is : £" +
        quoteAmountForPremium);
      Console.WriteLine();
      Console.WriteLine("The discount is : £" +
        quoteDiscount);
      Console.WriteLine();
      Console.WriteLine("The final discounted amount is : £" +
        quoteFinalAmountForPremium);
      Console.WriteLine("********************************** ");
    } // End of Main() method
  } // End of QuoteArithmetic class
} // End of Chapter8 namespace
Listing 8-10

Display output information

  1. 33.

    Click the File menu.

     
  2. 34.

    Choose Save All.

     
  3. 35.

    Click the Debug menu.

     
  4. 36.

    Choose Start Without Debugging.

     
  5. 37.

    Type 5 as the age of the vehicle.

     
  6. 38.

    Press the Enter key on the keyboard.

     
  7. 39.

    Type 60000 as the number of kilometers on the odometer.

     
  8. 40.

    Press the Enter key on the keyboard.

     
Figure 8-13 shows the console window with the quotation details.

An output window enlists the details for a car quotation application. It includes the age and mileage of the vehicle, and price quotations, among others.

Figure 8-13

Quotation output

  1. 41.

    Press the Enter key to close the console window.

     
Now let us pose the question: Is the quotation amount correct?
  • Well, we should have known what to expect, before we started the application.

  • We need to know the formula before we code, but we should also have test data that would tell us what to expect for the final quote.

  • If we followed a Test-Driven Development methodology, we would write tests first and then write the code that makes the tests pass.

It is imperative that we do not just accept that the console output is correct. An attitude of "It's in the console output, so it must be correct" is fundamentally wrong and a dangerous assumption. We need to verify the results. While we will not be using a Test-Driven Development approach, we still need to think like a software tester. Moving to a Test-Driven Development approach can only be achieved once we have built the core C# programming skills, and after gaining these skills, Test-Driven Development is just a different methodology to writing the same C# code that we will be producing throughout the chapters in the book.

Let’s check the mathematical calculations and see what the answer is:

quoteAgeFactor = 10/5 = 2.0

quoteAgeFactorPremium = £100 * 2.0 = £200

quoteMileageFactor = (60000/5)/ 10000 = 12000/10000 = 1.2

quoteMileageFactorPremium = £100 * 1.2 = £120

quoteAmountForPremium = £200 + £120 = £320

quoteDiscount = (1/5) * £320 = £64

quoteFinalAmountForPremium = £320 £64 = £256

Formatting the Output

What we also see is that our output does not have two figures after the decimal point. The WriteLine() method merely prints out a line of code but does not format it. If we wish to have formatted text, we can use some “special” code.

The WriteLine() method can be used in a different way, not using the concatenation, +, version we have used up to now. We can keep all the output between double quotes "", and when we wish to have a variable included, we add a placeholder within the double quotes. The placeholder is used to represent the variable that will be included after the double quote, following a comma. Figures 8-14, 8-15, and 8-16 show the placeholder code and output for three different examples.

A console window illustrates the use of the write line function to display the value stored in the variable quote amount for premium on the output window. Bubbles are used to indicate placeholder and variable locations on it.

Figure 8-14

WriteLine() with placeholder

A console window in which the line, console dot write line, open parenthesis, double quotes the quotation is, colon three backslash t's, 0 colon N 2 inside curly braces, double quotes comma quote amount for premium, close parenthesis, semicolon is written.

Figure 8-15

WriteLine() with placeholder and formatting to two decimal places

A console window in which the line, console dot write line, open parenthesis, double quotes the quotation is, colon, double quotes, plus sign, double quotes, three backslash t's, 0 colon C 2 inside curly braces, double quotes comma quote amount for premium, close parenthesis, semicolon is written.

Figure 8-16

WriteLine() with placeholder and currency formatting

The placeholder(s) matches the variable(s) in the list after the ending double quote and comma. The placeholder can also control the number of decimal places.
  1. 1.

    Amend the code, as in Listing 8-11, replacing some WriteLine() methods with the new format containing placeholders.

     
      Console.WriteLine("********************************* ");
      Console.WriteLine("Quotation is for 1 year from today ");
      Console.WriteLine("********************************* ");
      Console.WriteLine("The age of the vehicle is : {0}", vehicleAgeInYears);
      Console.WriteLine("The age factor for this vehicle is : {0}", quoteAgeFactor);
      Console.WriteLine();
      Console.WriteLine("The average kilometres per year is : {0:N2}", (vehicleCurrentMileage / vehicleAgeInYears));
      Console.WriteLine("The mileage factor is : {0:N2}", quoteMileageFactor);
      Console.WriteLine();
      Console.WriteLine("The quotation is : {0:C2}", quoteAmountForPremium);
      Console.WriteLine();
      Console.WriteLine("The discount is : {0:C2}" , quoteDiscount);
      Console.WriteLine();
      Console.WriteLine("The final discounted amount is : {0:C2}", quoteFinalAmountForPremium);
      Console.WriteLine("********************************* ");
    } // End of Main() method
  } // End of QuoteArithmetic class
} // End of Chapter8 namespace
Listing 8-11

Using placeholders

  1. 2.

    Click the File menu.

     
  2. 3.

    Choose Save All.

     
  3. 4.

    Click the Debug menu.

     
  4. 5.

    Choose Start Without Debugging.

     
  5. 6.

    Type 5 as the age of the vehicle.

     
  6. 7.

    Press the Enter key on the keyboard.

     
  7. 8.

    Type 60000 as the number of kilometers on the odometer.

     
  8. 9.

    Press the Enter key on the keyboard.

     
Figure 8-17 shows the console window with the quotation details formatted using decimal places and currency.

A console window has a column of values that is boxed. The bubbles beside them indicate that they are formatted to 2 decimal places and for currency.

Figure 8-17

Formatted output, two decimal places and currency

  1. 10.

    Press the Enter key again to close the console window.

     

Other Operators

Table 8-1 shows two interesting arithmetic operators included with C#.
Table 8-1

Add one and subtract one

Two arithmetic operators that are included with C#

++

Means add one to the value

Example

double quoteMileageFactor = 1.2;

quoteMileageFactor ++;

quoteMileageFactor will now be 2.2.

We will see this operator when we come to code with iteration and loops.

--

Means subtract one from the value

Example

double quoteMileageFactor = 1.2;

quoteMileageFactor --;

quoteMileageFactor will now be 0.2.

We can use this operator when we code with iteration and loops.

Postfix increment operator

++

When the ++ appears after the variable name, the action occurs and then the variable value is incremented, so with post-increment, the operation is performed and then the increment happens.

double quoteMileageFactor = 1.2;

// 1.2 is displayed, the value then increases to 2.2

Console.WriteLine(quoteMileageFactor++);

// 2.2 will be displayed

Console.WriteLine(quoteMileageFactor);

Prefix increment operator

++

When the ++ appears before the variable name, the variable value is incremented before any action, so with pre-increment, the increment is performed and then the operation happens.

double quoteMileageFactor = 1.2;

// 2.2 is displayed, the value then increases to 2.2

Console.WriteLine(++quoteMileageFactor);

// 2.2 will be displayed

Console.WriteLine(quoteMileageFactor);

Apart from the mathematical operators +, –, *, /, and %, there are other operators included in C#. We will now look at what are called assignment operators, which store a value in the object on the left-hand side. Up to now in our code, we have used one operator, the = symbol, for example:
quoteAgeFactorPremium = quoteBaseRate * quoteAgeFactor;
The = operator is a simple operator. Now we will use the compound assignment operators. In the code examples in Table 8-2, we will see the use of the compound assignment, where an arithmetic operation is performed before the value is stored in the object on the left-hand side.
Table 8-2

Compound assignment operators

Compound assignment operators

+=

Means take the value on the right of the = and add it to the value of the object on the left of the =, storing the new value in the object on the left

Example

double quoteMileageFactor = 1.2;

quoteMileageFactor += 1;

quoteMileageFactor will now be 2.2.

-=

Means take the value on the right of the = and subtract it from the value of the object on the left of the =, storing the new value in the object on the left

Example

double quoteMileageFactor = 1.2;

quoteMileageFactor -= 1;

quoteMileageFactor will now be 0.2.

*=

Means take the value on the left of the = and multiply it by the value on the right of the =, storing the new value in the object on the left

Example

double quoteMileageFactor = 1.2;

quoteMileageFactor *= 2;

quoteMileageFactor will now be 2.4.

/=

Means take the value on the left of the = and divide it by the value on the right of the =, storing the new value in the object on the left

Example

double quoteMileageFactor = 1.2;

quoteMileageFactor /= 2;

quoteMileageFactor will now be 0.6.

We will now amend our existing code to use some of the operators we have just read about, starting with Listing 8-12.

Plus Equals ( += )

  1. 11.

    Add a new code statement that uses the += operator, as in Listing 8-12.

     
      quoteMileageFactor = (vehicleCurrentMileage /
        vehicleAgeInYears) / quoteAverageExpectedKilometres;
      quoteMileageFactor += 1;
Listing 8-12

+= operator

  1. 12.

    Click the File menu.

     
  2. 13.

    Choose Save All.

     
  3. 14.

    Click the Debug menu.

     
  4. 15.

    Choose Start Without Debugging.

     
  5. 16.

    Type 5 as the age of the vehicle.

     
  6. 17.

    Press the Enter key on the keyboard.

     
  7. 18.

    Type 60000 as the number of kilometers on the odometer.

     
  8. 19.

    Press the Enter key on the keyboard.

     
Figure 8-18 shows the new calculations, after the increment of the variable quoteMileageFactor. We can see that the mileage factor has increased by 1 to become the value 2.2.

A console window has the value for mileage factor boxed with a bubble indicating, increased by 1 quote mileage factor, plus sign, equal sign, 1, semicolon.

Figure 8-18

+=1

  1. 20.

    Press the Enter key to close the console window.

     

Minus Equals ( -= )

  1. 21.

    Amend the one code line, as Listing in 8-13, to use the -= operator.

     
      quoteMileageFactor = (vehicleCurrentMileage /
        vehicleAgeInYears) / quoteAverageExpectedKilometres;
      quoteMileageFactor -= 1;
Listing 8-13

-= operator

  1. 22.

    Click the File menu.

     
  2. 23.

    Choose Save All.

     
  3. 24.

    Click the Debug menu.

     
  4. 25.

    Choose Start Without Debugging.

     
  5. 26.

    Type 5 as the age of the vehicle.

     
  6. 27.

    Press the Enter key on the keyboard.

     
  7. 28.

    Type 60000 as the number of kilometers on the odometer.

     
  8. 29.

    Press the Enter key on the keyboard.

     
Figure 8-19 shows the new calculations, after the decrement of the variable quoteMileageFactor. We can see that the mileage factor has decreased by 1 to become the value 0.2.

A console window has the value for mileage factor boxed with a bubble indicating, decreased by 1 quote mileage factor, minus sign, equal sign, 1, semicolon.

Figure 8-19

-=1

  1. 30.

    Press the Enter key to close the console window.

     

Multiply Equals ( *= )

  1. 31.

    Amend the one code line, as in Listing 8-14, to use the *= operator.

     
      quoteMileageFactor = (vehicleCurrentMileage /
        vehicleAgeInYears) / quoteAverageExpectedKilometres;
     quoteMileageFactor *= 2;
Listing 8-14

*= operator

  1. 32.

    Click the File menu.

     
  2. 33.

    Choose Save All.

     
  3. 34.

    Click the Debug menu.

     
  4. 35.

    Choose Start Without Debugging.

     
  5. 36.

    Type 5 as the age of the vehicle.

     
  6. 37.

    Press the Enter key on the keyboard.

     
  7. 38.

    Type 60000 as the number of kilometers on the odometer.

     
  8. 39.

    Press the Enter key on the keyboard.

     
Figure 8-20 shows the new calculations, after the increment of the variable quoteMileageFactor. We can see that the mileage factor has multiplied by 2, doubled, to become the value 2.4.

A console window has the value for mileage factor boxed with a bubble indicating, multiplied by 2 quote mileage factor, asterisk sign, equal sign, 2, semicolon.

Figure 8-20

*= operator

  1. 40.

    Press the Enter key to close the console window.

     

Divide Equals ( /= )

  1. 41.

    Amend the one code line, as in Listing 8-15, to use the /= operator.

     
      quoteMileageFactor = (vehicleCurrentMileage /
        vehicleAgeInYears) / quoteAverageExpectedKilometres;
      quoteMileageFactor /= 2;
Listing 8-15

/= operator

  1. 42.

    Click the File menu.

     
  2. 43.

    Choose Save All.

     
  3. 44.

    Click the Debug menu.

     
  4. 45.

    Choose Start Without Debugging.

     
  5. 46.

    Type 5 as the age of the vehicle.

     
  6. 47.

    Press the Enter key on the keyboard.

     
  7. 48.

    Type 60000 as the number of kilometers on the odometer.

     
  8. 49.

    Press the Enter key on the keyboard.

     
Figure 8-21 shows the new calculations, after the decrement of the variable quoteMileageFactor. We can see that the mileage factor has been divided by 2, halved, to become the value 0.6.

A console window has the value for mileage factor boxed with a bubble indicating, divided by 2 quote mileage factor, forward slash, equal sign, 2, semicolon.

Figure 8-21

/= operator

  1. 50.

    Press the Enter key to close the console window.

     

Square Root

Here we will use the Math class and its Sqrt() method. The Sqrt() method accepts a numeric value, which is to be operated on.
  1. 51.

    Amend the one code line, as in Listing 8-16, to use the Sqrt() method.

     
      quoteMileageFactor = (vehicleCurrentMileage /
        vehicleAgeInYears) / quoteAverageExpectedKilometres;
           quoteMileageFactor = Math.Sqrt(quoteMileageFactor);
Listing 8-16

Square root

  1. 52.

    Click the File menu.

     
  2. 53.

    Choose Save All.

     
  3. 54.

    Click the Debug menu.

     
  4. 55.

    Choose Start Without Debugging.

     
  5. 56.

    Type 5 as the age of the vehicle.

     
  6. 57.

    Press the Enter key on the keyboard.

     
  7. 58.

    Type 60000 as the number of kilometers on the odometer.

     
  8. 59.

    Press the Enter key on the keyboard.

     
Figure 8-22 shows the new calculations, after finding the square root of the variable quoteMileageFactor. We can see that the mileage factor has been calculated as the square root of 1.2, which is 1.1.

A console window has a value that is boxed and a bubble indicating: square root of 2, math, dot, s q r t, open parenthesis, quote mileage factor, close parenthesis.

Figure 8-22

Square Root

  1. 60.

    Press the Enter key to close the console window.

     
We will now change the format for the mileage factor, quoteMileageFactor, so we have 16 figures after the decimal point, just to illustrate that we do not necessarily always need or want to use two decimal places.
  1. 61.

    Amend the code, changing the 2 to 16 in the line of code, as in Listing 8-17.

     
Console.WriteLine("The average kilometres per year is: " +
" {0:N2}", (vehicleCurrentMileage/vehicleAgeInYears));
Console.WriteLine("The mileage factor is : {0:N16}" ,
quoteMileageFactor);
Listing 8-17

Square root to 16 decimal places

  1. 62.

    Click the File menu.

     
  2. 63.

    Choose Save All.

     
  3. 64.

    Click the Debug menu.

     
  4. 65.

    Choose Start Without Debugging.

     
  5. 66.

    Type 5 as the age of the vehicle.

     
  6. 67.

    Press the Enter key on the keyboard.

     
  7. 68.

    Type 60000 as the number of kilometers on the odometer.

     
  8. 69.

    Press the Enter key on the keyboard.

     
Figure 8-23 shows the new calculations, after finding the square root of the variable quoteMileageFactor and displaying the output with 16 figures after the decimal point.

A console window has the value of the mileage factor boxed with a bubble indicating the square root with 16 decimal places.

Figure 8-23

Square root to 16 decimal places

  1. 70.

    Press the Enter key again to close the console window.

     

Note

The other calculations that depend on the quoteMileageFactor still have the same value. This should indicate to us that even though two decimal places were displayed, the underlying figure was more accurate than the two decimal places.

Chapter Summary

In this chapter we have learned about the very important concept of arithmetic operations, which will be widely used in real-world applications. We also saw that arithmetic performed on variables or values can result in inaccuracies because the display does not show the required number of decimal places. We then saw the use of the {0:D}, {0:2D}, and {0:C} type placeholders where we could specify the number of decimal places required in the output. Besides the popular arithmetic operators +, -, *, and /, we also saw some “strange” operators, +=, -=, *=, and /=.

We are making great progress in our programming of C# applications and we should be proud of our achievements. In finishing this chapter and increasing our knowledge, we are advancing to our target.

An illustration of concentric circles with two differently colored regions above a text that reads, our target is getting closer.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.124.21