Lesson 9 - Arithmetic Operators

Tutorial Series: Free C# Fundamentals via ASP.NET Web Apps

Previous Article  |  Next Article

In this lesson, we will discuss arithmetic operators, which entail nothing more than common math calculations. There are a few other “fancier” math operations available, but we will simply cover operations most commonly used in business applications:

  • Addition

  • Subtraction

  • Multiplication

  • Division

Step 1: Create a New Project

For this lesson, you can either use the "Before" code provided and skip ahead, or create an ASP.NET application called “CS-ASP_009” using the previously detailed workflow. Add to this Project a Default.aspx file with the following Server Controls and programmatic IDs:

  1. TextBox - inputTextBox

  2. Button - okButton

  3. Label - resultLabel


Before going into math operations, it is important to distinguish the way you would normally think of the equal’s sign (=) with the way it is used in C#. In math, the equal’s sign is used to designate equivalence between elements on both sides of that symbol: 1 + 1 = 2

However, in C#, the equal’s sign is not used as an equivalence operator (there is another operator used for that operation). Rather, the equals sign designates assignment. This was touched upon in the previous lessons where it was mentioned that dumping the contents of one variable “bucket” into another assigns that value to it (int i = double j). Value assignment can be of any data type available, not just numerical values. For instance, a bool could be assigned the value of another bool variable using the equal's sign.

Step 2: Addition, Subtraction, Multiplication and Division in C#

With this in mind, let’s write out some basic math operations using familiar mathematical operators, then assign the results of those calculations to a variable “bucket”. You can write this out in the okButton_Click event in Default.aspx.cs.


Copy and paste the int result line four times, but change the mathematical operation each time. Then, comment out the previous "result" variable.





It might be helpful to read these statements from right-to-left. In other words, i + j is calculated first, then stored inside the variable on the left side of the equal's sign.

You can treat the variable used in the calculation as the literal value that it holds. That means that there is no essential difference between the formulations shown above, and one such as this:


You can also take whatever current value is contained inside a variable, perform an operation on that, and store it back to the original variable all in the same line of code:


Step 3: Using Calculation Assignment Shortcuts (+=, -=, ++, --)

There is a shortcut when performing this calculation, by combining the arithmetic operator with the assignment operator as follows:


The above example has the effect of incrementing by 1. In other words, it is shorthand for adding 1 to the current value of the variable. You have yet another shortcut for representing a single increment by writing this:


Or, you could decrement in much the same way:


Note that you can perform these operations, one after the other, as much as you want:



You can use the ++ and -- to decrement only by a value of 1, whereas with += and -=, you can increment or decrement by any value you choose, including another variable. Depending on the situation, one method may be more effective than another.

Step 4: Operator and Calculation Precedence

When performing calculations, it is important to be aware of operator precedence (also called “order of operation”, remember My Dear Aunt Sally?). For example, what do you think the result will be when running this code?



The answer is 12 because C# adheres to the operator precedence dictated by ordinary math. In other words, multiplication and division occur before addition and subtraction. However, what if we intended to first add 5 + 1, and then multiply the result of that with 7? You can create your own precedence by wrapping the calculation in parentheses, again, just like in ordinary math:



We get this result because we instructed Visual Studio to perform the operation inside the parentheses (in this case, addition) first, then follow order of operations as normal.

Step 5: Calculating with Mixed Data Types

Next, let’s see what happens when we mix a decimal value with a whole number in a calculation:



The calculation performs as we would expect because myInteger gets implicitly upcast to a double in order to make the calculation work, then the answer is stored in a double. However, let’s see what happens when we try to store this calculation to an int instead:


As you can see with the red squiggly underline, this produces compilation error immediately recognized by the compiler. It warns us that we are trying to implicitly convert myDouble to an int, however, we know that we can do the conversion ourselves by simply casting as follows:


This now works because we are downcasting myDouble to an int, but as you may recall from the previous lesson, this will result in truncating the decimal data:


You should always be aware of truncation occurring when dealing with integers, especially when dividing whole numbers and wanting a decimal value result:


When dealing with doubles we would expect the result of this division to be 1.75. However, because we are dealing with integers, the resulting calculation ignores the decimal data altogether, leaving us with 1:


You may be tempted to solve this problem by storing the result of the calculation into a double instead:


However, this still yields the same truncated result as before. The reason for this is because the calculation is still being performed on integers, and the result of the calculation will always be a whole number. Yes, the result is being stored as a double, but the calculation is being performed on ints, which must be whole numbers. After the calculation, the result assigned to the double. The way we fix this is by upcasting the ints to doubles:



Step 6: Calculating a Value That “Overflows the Bucket”

In the previous lesson, we confronted the possibility of data overflow, where a given data type isn’t large enough to store all of the information it is given. Recalling that an int is only capable of storing a number up to 2147483647, let’s see what happens when we overflow an int variable with a number that is too large:



You are probably quite confused by this result. While it is clear that the result of this calculation would be way outside the boundaries of what an int can store (2,147,000,000), why would it result in a negative value? The answer is quite technical and not necessarily helpful to a beginning programmer. Just be aware that this can happen when doing calculations that may involve larger numbers than you anticipated.


The moral of the story is that you should always use larger data types whenever you're performing arithmetic operations with the potential to overflow. It's best to assume that an error may occur and prepare for that in order to ensure your code will successfully run.

The most obvious way of solving this problem is to use the largest data type we know of for storing such a large number:



If you only cast the assigned-to variable (resultNumber) to a long, you will get the overflow, for a similar reason as we saw with truncation by dividing ints earlier, where the calculation is being performed on ints:



Step 7: Using “checked” to Catch Silent Overflows

Perhaps the most important thing to realize about these kinds of overflow problems is that they can happen quietly, without your knowledge, unless you take steps to:

  • Consider the possibility of it happening ahead of time

  • Use a “checking” measure to report when an overflow occurs

There is a built-in checking measure that you can use in C# called checked:


When the application runs, it will no longer be silent about the overflow. Instead, it will crash on this line of code, delivering an OverflowException:


Note: While having an exception occur might seem worse than simply letting the code run, it isn't. Programmers can respond to exceptions and keep record of them, as opposed to quietly letting the code deliver an incorrect result to the end-user. You'll find that exceptions are a tool, not a hindrance.


Don’t worry about how odd this code might look right now. This will become clearer when you learn about scope in a later lesson. This is just an illustration of the kinds of issues you can run into when you are not careful about properly handling your data types. In the end, no programmer can rely on foresight alone; apps will crash, users will submit bug reports, and mistakes will need to be weeded out accordingly. However, what programmers can do is account for these possibilities, and write safeguards to gracefully handle such occurrences.

There is more to arithmetic operations than what was covered in this lesson. However, with these basics under your belt, you will be well-equipped to tackle the majority of problems needing to be solved when working with numerical data types in the coming lessons. Great job, keep it up!

Related Articles in this Tutorial:

Lesson 1 - Series Introduction

Lesson 2 - Installing Visual Studio 2015

Lesson 3 - Building Your First Web App

Lesson 4 - Understanding What You Just Did

Lesson 5 - Working with Projects in Visual Studio

Lesson 6 - Simple Web Page Formatting in Visual Studio

Challenge 1

Solution 1

Lesson 7 - Variables and Data Types

Lesson 8 - Data Type Conversion

Lesson 9 - Arithmetic Operators

Lesson 10 - C# Syntax Basics

Challenge 2 - ChallengeSimpleCalculator

Solution - ChallengeSimpleCalculator

Lesson 11 - Conditional If Statements

Lesson 12 - The Conditional Ternary Operator

Challenge 3 - ChallengeConditionalRadioButton

Solution - Challenge Conditional RadioButton

Lesson 13 - Comparison and Logical Operators

Lesson 13 Challenge - First Papa Bob's Website

Solution - Challenge First Papa Bob's Website

Lesson 14 - Working with Dates and Times

Lesson 15 - Working With Spans of Time

Lesson 16 - Working with the Calendar Server Control

Challenge 4 - Challenge Days Between Dates

Solution - Challenge Days Between Dates

Lesson 17 - Page_Load and Page.IsPostBack

Lesson 18 - Setting a Break Point and Debugging

Lesson 19 - Formatting Strings

Challenge 5 - Challenge Epic Spies Assignment

Solution - Challenge Epic Spies Assignment

Lesson 20 - Maintaining State with ViewState

Lesson 21 - Storing Values in Arrays

Lesson 22 - Understanding Multidimensional Arrays

Lesson 23 - Changing the Length of an Array

Challenge 6 - Challenge Epic Spies Asset Tracker

Solution - Challenge Epic Spies Asset Tracker

Lesson 24 - Understanding Variable Scope

Lesson 25 - Code Blocks and Nested If Statements

Lesson 26 - Looping with the For Iteration Statement

Challenge 7 - Challenge For Xmen Battle Count

Solution - Challenge For Xmen Battle Count

Lesson 27 - Looping with the while() & do...while() Iteration Statements

Lesson 28 - Creating and Calling Simple Helper Methods

Lesson 29 - Creating Methods with Input Parameters

Lesson 30 - Returning Values from Methods

Lesson 31 - Creating Overloaded Methods

Lesson 32 - Creating Optional Parameters

Lesson 33 - Creating Names Parameters

Lesson 34 - Creating Methods with Output Parameters

Challenge 8 - Challenge Postal Calculator Helper Methods

Solution - Challenge Postal Calculator Helper Methods

Mega Challenge Casino

Solution - Mega Challenge Casino

Lesson 35 - Manipulating Strings

Challenge 9 - Phun With Strings

Solution - Challenge Phun With Strings

Lesson 36 - Introduction to Classes and Objects

Challenge - Hero Monster Classes Part 1

Solution - Hero Monster Classes Part 1

Challenge - Hero Monster Classes Part 2

Solution - Challenge Hero Monster Classes Part 2

Lesson 37 - Creating Class Files Creating Cohesive Classes and Code Navigation

Lesson 38 - Understanding Object References and Object Lifetime

Lesson 39 - Understanding the .NET Framework and Compilation

Lesson 40 - Namespaces and Using Directives

Lesson 41 - Creating Class Libraries and Adding References to Assemblies

Lesson 42 - Accessibility Modifiers, Fields and Properties

Lesson 43 - Creating Constructor Methods

Lesson 44 - Naming Conventions for Identifiers

Lesson 45 - Static vs Instance Members

Challenge 10 - Challenge Simple Darts

Solution - Challenge Simple Darts

Lesson 46 - Working with the List Collection

Lesson 47 - Object Initializers

Lesson 48 - Collection Initializers

Lesson 49 - Working with the Dictionary Collection

Lesson 50 - Looping with the foreach Iteration Statement

Lesson 51 - Implicitly-Typed Variables with the var Keyword

Challenge 11 - Challenge Student Courses

Solution - Challenge Student Courses

Mega Challenge War

Solution - Mega Challenge War

Lesson 52 - Creating GUIDs

Lesson 53 - Working with Enumerations

Lesson 54 - Understanding the switch() Statement

Lesson 55 - First Pass at the Separation of Concerns Principle

Lesson 56 - Understanding Exception Handling

Lesson 57 - Understanding Global Exception Handling

Lesson 58 - Understanding Custom Exceptions

Lesson 59 - Creating a Database in Visual Studio

Lesson 60 - Creating an Entity Data Model

Lesson 61 - Displaying the DbSet Result in an ASP.NET GridView

Lesson 62 - Implementing a Button Command in a GridView

Lesson 63 - Using a Tools-Centric Approach to Building a Database Application

Lesson 64 - Using a Maintenance-Driven Approach to Building a Database Application

Lesson 65 - Creating a New Instance of an Entity and Persisting it to the Database

Lesson 66 - Package Management with NuGet

Lesson 67 - NuGet No-Commit Workflow

Lesson 68 - Introduction the Twitter Bootstrap CSS Framework

Lesson 69 - Mapping Enum Types to Entity Properties in the Framework Designer

Lesson 70 - Deploying the App to Microsoft Azure Web Services Web Apps

Papa Bob's Mega Challenge

Papa Bob's Mega Solution Part 1 - Setting up the Solution

Papa Bob's Mega Solution Part 2 - Adding an Order to the Database

Papa Bob's Mega Solution Part 3 - Passing an Order from the Presentation Layer

Papa Bob's Mega Solution Part 4 - Creating the Order Form

Papa Bob's Mega Solution Part 5 - Adding Enums

Papa Bob's Mega Solution Part 6 - Creating an Order with Validation

Papa Bob's Mega Solution Part 7 - Calculating the Order Price

Papa Bob's Mega Solution Part 8 - Displaying the Price to the User

Papa Bob's Mega Solution Part 9 - Creating the Order Management Page


Please login or register to add a comment