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.
Brackets
pOwers
Division (division and multiplication have the same priority)
Multiplication
Addition (addition and subtraction have the same priority)
Subtraction
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.
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.
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.
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
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.
19%5 will give an answer of 4.
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.
- 1.
Right-click the solution CoreCSharp.
- 2.
Choose Add.
- 3.
Choose New Project, as shown in Figure 8-1.
- 4.
Choose Console App from the listed templates that appear, as shown in Figure 8-2.
- 5.
Click the Next button.
- 6.
Name the project Chapter8 and leave it in the same location, as shown in Figure 8-3.
- 7.
Click the Next button.
- 8.
Choose the framework to be used, which in our projects will be .NET 6.0 or higher, as shown in Figure 8-4.
- 9.
Click the Create button.
- 10.
Right-click the Chapter8 project in the Solution Explorer panel.
- 11.
Click the Set as Startup Project option.
Solution Explorer and Project Analysis
- 12.
Right-click the solution name.
- 13.
Choose Open Folder in File Explorer, or Finder on a Mac, as shown in Figure 8-8.
- 14.
Open the Chapter8 folder in File Explorer, or Finder on a Mac.
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 .
- 15.
Double-click the Chapter8 Program.cs file in the Solution Explorer window to open it in the editor window.
- 16.
Right-click the Chapter8 Program.cs file in the Solution Explorer window.
- 17.
Choose Rename.
- 18.
Change the name to Arithmetic.cs.
- 19.
Press the Enter key.
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:
- 20.
Right-click the Arithmetic.cs file in the Solution Explorer window.
- 21.
Choose Rename.
- 22.
Change the name to QuoteArithmetic.cs, as shown in Figure 8-12.
- 23.
Press the Enter key.
First is a namespace.
Inside the namespace will be a class – here it is QuoteArithmetic.
Inside the class will be the Main() method.
- 24.
In the QuoteArithmetic editor window, add the code in Listing 8-2.
QuoteArithmetic.cs structure with class and namespace
- 25.
In the editor window, add the variables as shown in Listing 8-3.
Declaring the variables in the Main() method
- 26.
Amend the code, as in Listing 8-4, adding print lines to the end of the code.
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.
- 27.
Amend the code, as in Listing 8-5, adding the lines to the end of the code.
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.
- 28.
Amend the code, as in Listing 8-6, to get the input and perform the two calculations.
Get user input for the mileage and perform calculations
- 29.
Amend the code , as in Listing 8-7, to calculate the quote amount.
Calculate the quote amount for the premium
- 30.
Amend the code, adding a quote discount formula to the end of the code, as in Listing 8-8.
Calculate the quote discount and use casting
- 31.
Amend the code, as in Listing 8-9, to perform the calculation for the final premium amount.
Calculate the quote final amount
- 32.
Amend the code, as in Listing 8-10, to add some print lines displaying a quotation.
Display output information
- 33.
Click the File menu.
- 34.
Choose Save All.
- 35.
Click the Debug menu.
- 36.
Choose Start Without Debugging.
- 37.
Type 5 as the age of the vehicle.
- 38.
Press the Enter key on the keyboard.
- 39.
Type 60000 as the number of kilometers on the odometer.
- 40.
Press the Enter key on the keyboard.
- 41.
Press the Enter key to close the console window.
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.
- 1.
Amend the code, as in Listing 8-11, replacing some WriteLine() methods with the new format containing placeholders.
Using placeholders
- 2.
Click the File menu.
- 3.
Choose Save All.
- 4.
Click the Debug menu.
- 5.
Choose Start Without Debugging.
- 6.
Type 5 as the age of the vehicle.
- 7.
Press the Enter key on the keyboard.
- 8.
Type 60000 as the number of kilometers on the odometer.
- 9.
Press the Enter key on the keyboard.
- 10.
Press the Enter key again to close the console window.
Other Operators
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); |
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 ( += )
- 11.
Add a new code statement that uses the += operator, as in Listing 8-12.
+= operator
- 12.
Click the File menu.
- 13.
Choose Save All.
- 14.
Click the Debug menu.
- 15.
Choose Start Without Debugging.
- 16.
Type 5 as the age of the vehicle.
- 17.
Press the Enter key on the keyboard.
- 18.
Type 60000 as the number of kilometers on the odometer.
- 19.
Press the Enter key on the keyboard.
- 20.
Press the Enter key to close the console window.
Minus Equals ( -= )
- 21.
Amend the one code line, as Listing in 8-13, to use the -= operator.
-= operator
- 22.
Click the File menu.
- 23.
Choose Save All.
- 24.
Click the Debug menu.
- 25.
Choose Start Without Debugging.
- 26.
Type 5 as the age of the vehicle.
- 27.
Press the Enter key on the keyboard.
- 28.
Type 60000 as the number of kilometers on the odometer.
- 29.
Press the Enter key on the keyboard.
- 30.
Press the Enter key to close the console window.
Multiply Equals ( *= )
- 31.
Amend the one code line, as in Listing 8-14, to use the *= operator.
*= operator
- 32.
Click the File menu.
- 33.
Choose Save All.
- 34.
Click the Debug menu.
- 35.
Choose Start Without Debugging.
- 36.
Type 5 as the age of the vehicle.
- 37.
Press the Enter key on the keyboard.
- 38.
Type 60000 as the number of kilometers on the odometer.
- 39.
Press the Enter key on the keyboard.
- 40.
Press the Enter key to close the console window.
Divide Equals ( /= )
- 41.
Amend the one code line, as in Listing 8-15, to use the /= operator.
/= operator
- 42.
Click the File menu.
- 43.
Choose Save All.
- 44.
Click the Debug menu.
- 45.
Choose Start Without Debugging.
- 46.
Type 5 as the age of the vehicle.
- 47.
Press the Enter key on the keyboard.
- 48.
Type 60000 as the number of kilometers on the odometer.
- 49.
Press the Enter key on the keyboard.
- 50.
Press the Enter key to close the console window.
Square Root
- 51.
Amend the one code line, as in Listing 8-16, to use the Sqrt() method.
Square root
- 52.
Click the File menu.
- 53.
Choose Save All.
- 54.
Click the Debug menu.
- 55.
Choose Start Without Debugging.
- 56.
Type 5 as the age of the vehicle.
- 57.
Press the Enter key on the keyboard.
- 58.
Type 60000 as the number of kilometers on the odometer.
- 59.
Press the Enter key on the keyboard.
- 60.
Press the Enter key to close the console window.
- 61.
Amend the code, changing the 2 to 16 in the line of code, as in Listing 8-17.
Square root to 16 decimal places
- 62.
Click the File menu.
- 63.
Choose Save All.
- 64.
Click the Debug menu.
- 65.
Choose Start Without Debugging.
- 66.
Type 5 as the age of the vehicle.
- 67.
Press the Enter key on the keyboard.
- 68.
Type 60000 as the number of kilometers on the odometer.
- 69.
Press the Enter key on the keyboard.
- 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.