Basic Math in C#

Basic Math in C#

The Crash Course

  • Arithmetic in C# is very similar to virtually every other programming language out there, particularly C++, C, and Java.
  • Addition works like this: int a = 3 + 4;
  • Subtraction works like this: // int b = 7 - 2;
  • Multiplication uses the asterisk character ('*') like this: //int c = 4 * 3;
  • Division uses the forward slash character ('/') like this: int d = 21 / 7;
  • The modulus operator ('%') gets the remainder of a division operation like this: int e = 22 % 7; (In this case, the variable e will be 1.)
  • You can use any of the standard numerical types (double, float, int, short, etc.) for doing math.
  • You can combine multiple operations into one, as well as use a previously created variable in a statement: int f = 3 * b - 4;
  • Order of operations matters, and it works just like you learned in math class, with multiplication and division happening before addition and subtraction, in a left to right order. Parentheses come even before multiplication and division, so you can use parentheses to make something happen before something else: double m = (y2 - y1) / (x2 - x1);
  • Compound assignment operators (+=, -=, /=, *=, and %=) do the desired operation and assign it to the variable on the left. So for instance, a += 3; is the same as a = a + 3;, and essentially adds 3 to the value of a.
  • More issues with math in C# will be discussed in a couple of tutorials.

Introduction

With a basic understanding of variables behind us, we're ready to get in to some deeper material: math. This math is all pretty easy—the kind of stuff you learned in elementary school. Basic arithmetic.

Computers love math. In fact, it is basically all they can do. But they do it ridiculously fast.

In this tutorial, we'll cover how to do some basic arithmetic in C#, starting with addition and subtraction, and move up through multiplication and division, a new operation called the modulus operator, positive and negative numbers, order of operations, and conclude with some compound assignment operators, which do math and assign a value all at once.

Addition, Subtraction, Multiplication, and Division

Doing the basic operations of addition, subtraction, multiplication, and division should be pretty straightforward, especially if you have done other programming before.

Let's start with a simple math problem that you probably did in second grade. The following code adds the numbers '3' and '4' and stores it into the variable called a:

int a = 3 + 4;

The same thing works for subtraction:

int b = 5 - 2;

You can also use variables in your math. You don't just have to use numbers.

int c = a + 4;
int d = a - b;

And that's not all. You can chain many operations together on one line:

int sum = 1 + 2 - 3 + 4 - 5 + a - b + c - d;

Multiplication and division work in the exact same way, though there's a few tricks we need to watch out for if we do division with integers. We'll look at that more in a couple of tutorials, but for now, we'll just use the float or double type for division instead of integers. The sign for multiplication in C# is the asterisk ("*") and the sign for division in C# is the forward slash ("/").

float totalCost = 22.54f;
float tipPercent = 0.18f; // Remember, this is the same as 18%
float tipAmount = totalCost * tipPercent;
double moneyMadeFromGame = 100000; // Note that you DO NOT put commas in the number.  C# won't know what to do with it
double totalProgrammers = 4;
double moneyPerPerson = moneyMadeFromGame / totalProgrammers; // We're rich!

Remember back when we did our first "Hello World!" program, and we used Console.WriteLine to show some text to the user? We can still do that with these numbers, too.

// The formula for the area of a circle is pi * r ^ 2
float radius = 4;
float pi = 3.1415926536f;  // The 'f' at the end makes it treat it as a float instead of a double.
float area = pi * radius * radius;
 
// Note how using '+' with a string (text) "concatenates" the number on the end of the text.
Console.WriteLine("The area of the circle is " + area);

In the above code snippet, we have variables for the radius of a circle, the value of the number PI, and the area, which we calculate, using a standard formula from geometry class. We then print out the result for the user.

Notice, too, that we've been able to use the '+' operator with strings (text). This is a cool feature of C#. It knows that you can't "add" strings in a mathematical sense, but there is an intelligent way of handling it, which is to concatenate the text together, so that one follows the other. If you run this code, you will see that the result is the computer prints out "The area of the circle is 50.26548". There's a little more going on here than just that, but we'll discuss it more in a couple of tutorials.

The Modulus Operator

Do you remember in elementary school, not too long after you first learned division, how you always did things like: "23 divided by 7 is 3 remainder 2"? Well in programming, calculating the remainder has its own operator, just like division. This operator is called the "modulus" operator (or "mod" for short). This operator only gives you back the remainder, not the division result. The sign for this operator is the percent sign ("%"). So it is important to remember that in C#, % does not mean "percent", it means "get the remainder of".

(As a refresher, 21 divided by 7 is 3, and there are two remaining to get up to 23. I know this may seem insanely simple for those who have been doing math forever, but not everyone is at the same level, and I'd hate to leave anyone behind at such an early point. Say you have 23 apples, and 7 people want the apples, this means everyone gets 3, and there are 2 remaining, or left over.)

Here's how you'd do this in C#:

int totalApples = 23;
int people = 7;
int remainingApples = totalApples % people; // this will be 2.

At first glance, it seems like an operator that's not very useful, but if you know how to use it, you will find lots of ways to use it.

Unary "+" and "-" Operators

You've already sort of seen these operators, but it is worth going into them a little bit more. A "unary" operator means one that only has one "operand" or number to work on. All of the ones we've discussed so far have been "binary" operators, meaning they have two operands. (For example, 2 + 3—this operator does something with the number before it and the number after it.)

Unary operators only work on a single operand, which comes right after it. I'll show you an example, and I think it will probably make perfect sense then:

// These are the unary '+' and unary '-' operators.  They only work on the number right after them.
int a = +3;
int b = -44;
 
// These are the binary '+' and binary '-' operators, also called addition and subtraction that work on two numbers around them.
int a = 3 + 4;
int b = 2 - 66;

The unary '+' and unary '-' are simply the sign of the number (+ or -) that they are in front of. We'll see at least one other unary operator later on.

Order of Operations and Parentheses

Perhaps you remember order of operations from math classes. Programming has the same thing, too, and it follows the same rules as math. As a refresher, with any mathematical equation or formula, you do the things in parentheses first, then powers and exponents (though C# doesn't have a built-in power operator—we'll discuss this more in a couple of tutorials), followed by multiplication and division, followed by addition and subtraction. C# follows these same rules.

Like in math, you can use parentheses to show that a particular part of the equation should be done first. For instance:

// Some simple code for the area of a trapezoid (http://en.wikipedia.org/wiki/Trapezoid)
// Don't worry if you don't remember this equation.
double side1 = 5.5;
double side2 = 3.25;
double height = 4.6;
 
double areaOfTrapezoid = (side1 + side2) / 2 * height;

In math, if you want an especially complicated formula with lots of parentheses, a lot of times you'll use square brackets ('[' and ']') and curly braces ('{' and '}') as "more powerful" parentheses. In C#, like most programming languages, that's not how it's done. Instead, you just put in multiple sets of nested parentheses, like below. Just be extra careful with multiple sets of parentheses to make sure everything matches up correctly.

// This isn't a real formula for anything.  I'm just making it up for an example...
double a =3.2;
double b = -4.3;
double c = 42;
double d = -91;
double e = 4.343;
 
double result = (((a + b) * (c - 4)) + d) * e;

Why the '=' Sign Doesn't Mean Equals

I mentioned in an earlier tutorial that the '=' sign doesn't mean that the two things equal each other. Not directly. It is thought of as an assignment operator instead, meaning that the stuff on the right gets calculated and put into the variable on the left side of the '=' sign.

Watch how this works:

int a = 5;
a = a + 1; // the variable a will have a value of 6 after running this line.

If you are a mathematician, you'll notice how strange that looks. From a math standpoint, it is impossible for a variable to equal itself plus 1. (For you math people out there, subtract a from both sides and you'll see that it shows 0 = 1.) It doesn't make sense. From a math standpoint.

But from a programming standpoint, it makes complete sense, because what we are really saying is "take the value currently in a (5), add one to it (to get 6), and assign that value back into the variable a." So after running that line, we've taken a and added one to it.

Compound Assignment Operators

What I just described, where you want to take a value and do something to it, and store it back in the original variable, is so common that there is a whole set of other operators that make it happen more easily. These operators are called compound assignment operators, because they perform a math function and assign a value all at once.

Here's how they work:

int a = 5;
a += 3; // This is the same as a = a + 3;

There's also equivalent ones for subtraction, multiplication, division, and the modulus operator:

int b = 7;
b -= 3; // This is the same as b = b - 3;  At this point b would be 4.
b *= 5; // This is the same as b = b * 5; At this point b would be 20.
b /= 4; // This is the same as b = b / 4;  At this point b would be 5.
b %= 2; // This is the same as b = b % 2;  At this point b would be 1.

What's Next?

This tutorial has covered a lot of math. But in fact, we're just getting started with math in C#. Our next step is going to be to take a bit of a detour, and learn how to get input from the user through the command prompt. In a full-fledged Windows application or XNA game, you'll get input from the user in much better ways, but right now, the command prompt is all we've got, so we need to be sure we know how to use it. (We'll get to the cooler stuff before too long.) Then we'll come back and learn a few more advanced things and sort of round out our knowledge of math that will be helpful to us as we make programs in C#.