Working with C Sharp Math Operators

We discussed C# data types in a previous article and today we will be following this up with a .Net tutorial that shows developers how to work with one of the data types we covered: numeric data types. Specifically, we will be learning how to use C# math operators and perform mathematical operations using C#. We will have plenty of code examples for you to practice along with, so open up your favorite integrated development environment (IDE) or code editor and let’s get started!

If you missed our previous articles in this series, we encourage you to read them. Likewise, if you need to refresh your memory, you can always revisit them by following the links below:

Math Operators in C#

Below you will find code examples showing how to work with the various math and numeric operators in C#. Some of them work in a similar manner to the mathematical operators you are used to from school and every day life. Others, while they may seem similar, work in unexpected and even surprising ways. We will begin with one of the most used operators in all of C# – the assignment operator.

Assignment Operator in C#

You have no doubt seen the assignment operator many times in your life; it is written using the equals sign or =. There are several assignment operators available in C# and the most basic is used to assign a simple value to a variable. The item to the left of the = sign is the variable name, while the value to the right of the = sign is the value that you want to assign to the variable. Here is how you use the basic assignment operator in C# code:

 
using System;
 
public class Program
{
            	public static void Main()
            	{
                            	int age = 44;
                                            	
                            	Console.WriteLine("Age is equal to: {0}", age);
            	}
}
 

In this code, we create an integer variable named age and assign it the value 44. This is achieved in the line that says int age = 44;. Next, we use the print statement Console.WriteLine to print some text and the value of our variable to the screen. Running this code in your code editor would result in the following output:

Age is equal to 44

You can also use other variables to assign a value to a variable using the assignment operator, as shown in the following example:

using System;
 
public class Program
{
            	public static void Main()
            	{
                            	int age = 44;
                            	int ageTwo = 44;
                            	int futureAge = age + ageTwo;	
                            	Console.WriteLine("Age is equal to: {0}", age);
                            	Console.WriteLine("Your age in another 44 years will be: {0}", futureAge);
            	}
}

In this example, we have created three variables. The first variable, age, represents my age. The second variable, ageTwo, represents my age when I am twice as old as I am now. Finally, we create a third variable, futureAge, which we assign the value of age + ageTwo – this shows that you can assign the value of one or more variables to another variable with the assignment operator. The result of running this code is:

Age is equal to: 44
Your age in another 44 years will be: 88

Another way to assign the value of an existing variable to a new variable would be to simply do the following:

using System;
 
public class Program
{
            	public static void Main()
            	{
                            	int age = 44;
                            	int ageTwo = age;
                            	
                            	Console.WriteLine("Age is equal to: {0}", age);
                            	Console.WriteLine("ageTwo is equal to: {0}", ageTwo);
            	}
}

This results in:

Age is equal to: 44
ageTwo is equal to: 44

The Addition + Operator in C#

The addition operator – or + operator – is used in a similar fashion to its mathematical equivalent you have been using your entire life. You can use it to add two or more numbers to one another when you apply it to an integer value or a floating-point number. Note that there is a difference when you use the + operator on an int versus when you use it on a float. We will discuss that difference momentarily. First, however, check out the following example where we demonstrate how to use the C# mathematical + operator:

 
using System;
 
public class Program
{
            	public static void Main()
            	{
                            	int valueOne = 12;
                            	int valueTwo = 8;
                            	
                            	Console.WriteLine("valueOne added to valueTwo is equal to: {0}", valueOne+valueTwo);
                            	
            	}
}

The result of this code, which adds the values of two integers together, is:

valueOne added to valueTwo is equal to: 20

Another way to use the + operator on an int in C# is by using it to assign a value to a variable. Check out the following code example:

using System;
 
public class Program
{
            	public static void Main()
            	{
                            	int valueOne = 8+12;
                                                            	
                            	Console.WriteLine("The value of valueOne is equal to: {0}", valueOne);
                            	
            	}
}

Here, we create a variable named valueOne and assign is the result of the equation 8+12. The result of running this in your IDE is:

The value of valueOne is equal to: 20

Anytime that you add an integer value to another integer, the result will always be an integer value. However, if you add an integer to a floating-point number, the result is always a float. Try running the following code to see this at work:

 
using System;
 
public class Program
{
            	public static void Main()
            	{
                            	int valueInteger = 8;
                            	float f2 = 1.02f;              	
                            	Console.WriteLine("The valueInteger plus f2 equals: {0}", valueInteger + f2);
                            	
            	}
}

Running this code will create the following output:

 
The valueInteger plus f2 equals: 9.02
 

A final thing to take note of: adding two floating point numbers will, as you might imagine, always result in a float.

The subtraction – operator in C#

The subtraction operator – or – operator – in C# works much as you would expect it to. Its purpose is to perform subtraction in a mathematical equation. Again, it works the same as its math equivalent. Like the + operator, when you subtract an integer from an integer, you always return an integer value. However, subtracting an integer from a floating-point number (or vice versa), the value is always a floating-point number.

Here is how you subtract two integer values from one another with the – operator in C#:

using System;
 
public class Program
{
            	public static void Main()
            	{
                            	int valueInteger1 = 8;
                            	int valueInteger2 = 12;               	
                            	Console.WriteLine("valueInteger2 minus valueInteger1 equals: {0}", valueInteger2 - valueInteger1);
                            	
            	}
}

The output of this code is:

valueInteger2 minus valueInteger1 equals: 4

Here is some code showing what happens when you subtract an integer from a float or vice versa:

using System;
 
public class Program
{
            	public static void Main()
            	{
                            	int valueInteger1 = 8;
                            	float floatValue = 1.02f;             	
                            	Console.WriteLine("valueInteger1 minus floatValue equals: {0}", valueInteger1 - floatValue);
                            	
            	}
}

Here, the result of running this code is:

valueInteger1 minus floatValue equals: 6.98

Finally, you can also assign a value to a variable by subtracting two variables from one another and storing the result of the equation in a variable. Here is how that looks in code:

using System;
 
public class Program
{
            	public static void Main()
            	{
                            	int valueInteger1 = 8;
                            	int valueInteger2 = 12;               	
                            	int valueInteger3 = valueInteger2 - valueInteger1;
                            	Console.WriteLine("valueInteger3 is equal to: {0}", valueInteger3);
                            	
            	}
}

This code adds the result of the equation 12 – 8 – or valueInteger2 – valueInteger1 – to the variable named valueInteger3. The result of running this code in your IDE?

valueInteger3 is equal to: 4

The Mulitplication * Operator in C#

The mutiplication operator – or * operator – performs multiplication on two or more values, just as it does in mathematical equations, though you may also have used x for multiplying numbers in school, as in 4 x 2 = 8. When you multiply two integers together, your result is always an integer. However, when you multiply an integer by a floating-point number, the result is always a floating-point number. Multiplying two or more decimals, meanwhile, always results in a decimal value.

Here is an example showing how to use the multiplication * operator in C# on two integer values:

using System;
 
public class Program
{
            	public static void Main()
            	{
                            	int valueInteger1 = 8;
                            	int valueInteger2 = 12;               	
                            	
                            	Console.WriteLine("valueInteger1 times valueInteger2 is equal to: {0}", valueInteger1 * valueInteger2);
                            	
            	}
}

Here is the result of running this code:

valueInteger1 times valueInteger2 is equal to: 96

Likewise, here is some code showing what happens when you multiply an integer by a floating-point number in C#

 
using System;
 
public class Program
{
            	public static void Main()
            	{
                            	int valueInteger1 = 8;
                            	float valueFloat = 1.2f;               	
                            	
                            	Console.WriteLine("valueInteger1 times valueFloat is equal to: {0}", valueInteger1 * valueFloat);
                            	
            	}
}

The outcome of this code snippet is:

valueInteger1 times valueFloat is equal to: 9.6

Finally, as with the + operator and the – operator, you can of course assign a value to a variable by assigning it the result of two variables multiplied by one another. Here is a sample of that in code:

 
using System;
 
public class Program
{
            	public static void Main()
            	{
                            	int valueInteger1 = 8;
                            	int valueInteger2 = 4;                  	
                            	int valueInteger3 = valueInteger1 * valueInteger2;
                            	Console.WriteLine("valueInteger3 is equal to: {0}", valueInteger3);
                            	
            	}
}
 

The result of running this code would give you:

valueInteger3 is equal to: 32

The Division / Operator in C#

The division operator – or / operator – is used to divide two or more numeric values. When using the division operator, be aware that dividing an integer by an integer always results in an integer – even if there is a remainder. In the event of a remainder, C# rounds down. Consider the following code:

using System;
 
public class Program
{
            	public static void Main()
            	{
                            	int valueInteger1 = 7;
                            	int valueInteger2 = 4;                  	
                            	int valueInteger3 = valueInteger1 / valueInteger2;
                            	Console.WriteLine("valueInteger3 is equal to: {0}", valueInteger3);
                            	
            	}
}

Normally, if you divided 7 / 4, you would expect to get a result of 1 with a remainder of three. However, since we are dividing two integers, all that C# can return is an integer, so you get the following result instead:

valueInteger3 is equal to: 1

If you divide an integer by a floating-point number, you always receive a floating-point number:

using System;

public class Program
{
public static void Main()
{
int valueInteger1 = 7;
float valueFloat = 4.0f;

Console.WriteLine("valueInteger1 / valueFloat is equal to: {0}", valueInteger1 / valueFloat);

}
}

The result of this code is:

valueInteger1 / valueFloat is equal to: 1.75

Finally, you can assign a value to a variable by dividing two numbers and assigning their value to a variable:

using System;
 
public class Program
{
            	public static void Main()
            	{
                            	int valueInteger1 = 7;
                            	int valueInteger2 = 4;                  	
                            	int valueInteger3 = valueInteger1 / valueInteger2;
                            	Console.WriteLine("valueInteger3 is equal to: {0}", valueInteger3);
                            	
            	}
}

This results in the following output:

valueInteger3 is equal to: 1

The Modulo % Operator in C#

If you do want to retrieve the remainder from a division, you are in luck, because C# has a built-in math operator for just such a function: the modulo operator – or % operator. Note that using this mathematical operator only returns the remainder from the division and nothing more. Here is how you use the modulo operator in C#:

using System;
 
public class Program
{
            	public static void Main()
            	{
                            	int valueInteger1 = 7;
                            	int valueInteger2 = 4;                  	
                            	
                            	Console.WriteLine("The remainder of valueInteger1 / valueInteger2 is: {0}", valueInteger1 % valueInteger2);
                            	
            	}
}

Since 7 / 4 equals 1 with a remainder of 3, using the modulo will result in the output:

The remainder of valueInteger1 / valueInteger2 is: 3

Remember – only the remainder is returned when using the modulo operator.

Of course, we can use modulo to create a variable as well:

using System;
 
public class Program
{
            	public static void Main()
            	{
                            	int valueInteger1 = 7;
                            	int valueInteger2 = 4;                  	
                            	int valueInteger3 = valueInteger1 % valueInteger2;
                            	Console.WriteLine("The value of valueInteger3 is: {0}", valueInteger3);
                            	
            	}
}

The result of this code is:

The value of valueInteger3 is: 3

Other Assignment Operators in C#

In addition to the basic or normal assignment operator we discussed at the beginning of this tutorial, C# also offers a slew of other assignment operators. We do not have space left in this article to cover all of them, so we will have to follow up with another article to show you the rest of them. However, we can show you a few here, and give you a sneak peek of the others. Note that not all assignment operators are mathematical in nature, which is another reason we will not review them here. Some belong to Bitwise and Shift operators.

The remaining C# assignment operators include:

  • = operator A regular assignment operator.
  • += Addition assignment operator
  • -= Subtraction assignment operator
  • *= Multiplication assignment operator
  • /= Division assignment operator
  • %= Modulo assignment operator

Run the following code to see each of these C# assignment operators in action:

using System;
 
public class Program
{
            	public static void Main()
            	{
                            	int additionAssignmentExample = 0;
                            	int subtractionAssignmentExample = 0;
                            	int multiplicationAssignmentExample = 1;
                            	int divisionAssignmentExample = 1;
                            	int moduloAssignmentExample = 1;
                            	
                            	Console.WriteLine(additionAssignmentExample +=5);
                            	Console.WriteLine(subtractionAssignmentExample -=5);
                            	Console.WriteLine(multiplicationAssignmentExample *=5);
                            	Console.WriteLine(divisionAssignmentExample /=5);
                            	Console.WriteLine(moduloAssignmentExample %=5);
            	}
}

The result of this code is:

5
-5
5
0
1

The += operator works by basically saying x = x +5 in this example. For instance, we started off by assigning additionAssignmentExample the value of 0. We then use the += assignment operator to add assign the value of additionAssignmentExample to itself, plus add 5 to it.

The rest of the assignment operators work in a similar fashion, only they subtract, multiply, divide, or return the modulo of the number to the right of the = sign.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read