# Basic Math

## 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 into 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 the result in 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 are 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: 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 that, but we'll discuss it more in a few 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 seen these operators, but it is worth going into them a bit more. A *unary* operator is one that uses only a single *operand* or number. All of the operators we've seen until now have been *binary* operators, which work on two numbers at a time. (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, and they work on the two numbers around them. int a = 3 + 4; int b = 2 - 66;

The unary `+` and unary `-` are simply the sign of the number (the + 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 the 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 parentheses to ensure 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. Instead, it is thought of as an assignment operator, 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, do something to it, and store it back in the original variable, is so common that a whole set of other operators 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 are 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#.

Nice explained, but i need to understand why you use int sometimes anf float, double other times. It makes no sence for me

ReplyOptionsThat's an excellent question, and it's one of many things I get into more detail on in my book.

Honestly, in this particular tutorial, I chose

int,double, andfloatat random. I was mostly just picking different types as a way to show that they can all be used in this math stuff. So if your question here is, "Why in these specific cases did you chooseintor whatever?" the answer is, "there is no real reason. I just picked them at random."At a more general level though, there is some method to choosing which type to use.

Your first real choice is between the integer types (int, short, long, byte, uint, etc.) and the floating point types (float, double, decimal). You make this decision based on whether you can be certain you're only going to use integers (whole numbers and their negatives) in which case you'll need one of the integer types, or if you need fractional/decimal numbers, in which case you'll need one of the floating point types.

Once this decision has been made, it all boils down to accuracy and range of values that you need.

The signed integer types, sbyte, short, int, and long, all allow you to supply a negative value, while the unsigned integer types do not (byte, ushort, uint, and ulong). If you know you need negative values, then you simply aren't going to be able to use the unsigned integer types, and must choose one of the signed versions. From there, its a matter of looking at their ranges and deciding which one has you covered, but that keeps the memory usage small. sbyte and byte use only one byte, short and ushort use two, int and uint use four, and long and ulong use eight. byte gets you up to 256. The short type goes from roughly -32,000 to +32,000. The int type goes from roughly -2 billion to +2 billion. The long type goes from roughly -9 quintillion to +9 quintillion.

On the floating point side,

floatgives you 7 digits of precision, whiledoublegives you 15 or 16 (depending on a variety of things).floatcan get up to 3.4 * 10^38, which is a huge number, butdoublecan go up to 1.7 * 10^308. Sodoublegives you an absolutely massive range, even way greater thanfloatwhich was already gigantic,plusit gives you a lot more precision. But adoubleis 8 bytes compared to 4 for afloat.Choosing types is all about finding the right balance between the data ranges and requirements, balanced against memory usage.

Let me rephrase all of this in a more practical way though.

In most cases, you don't have to worry too much about a few extra bytes here and there. There's enough memory that a little extra memory isn't going to hurt you much.

Because of this, most programmers tend to use

intwhen they can use an integer type (as opposed to trying to optimize too much and usingshortorbyte. Even if you don't think you're using negative numbers, and could theoretically use one of the unsigned types likeushortoruint, most programmers won't actually use these types unless they can basically guarantee that their numbers fit into the range of those types exactly.Most programmers won't use

longorulongunless either some sort of spec dictates it (like an RFC for networking packets) or they bump into a problem whereintturned out not to be good enough.intseems to always be the default.The

bytetype is almost never used, except when you're serializing stuff to a byte stream, like you might do when communicating between client and server. In those cases, you won't often see just a single byte, but a byte array.On the floating point side,

floatused to be more common, but in recent years (the last decade or two) as memory has become very cheap,doublehas become the norm. I personally usedoublewhenever I have to choose between the two. The only time I end up usingfloatis when something I'm working with requires it. And when you're working with DirectX and OpenGL, that's the size of data that they always use. So that's when I'll drop down tofloat.I've only really found one or two uses for

decimal. It's a type that's designed for difficult calculations involving money. Interest calculations and things like that. It has a much smaller range than bothdoubleanddecimal, but with way more precision than either.So.

Bottom line: Most programmers will default to

intin the integer world anddoublein the floating point world. Various other things might force you to consider using smaller or larger ranges in certain scenarios, which would drive you to one of the alternative choices, depending on the specifics of your situation.Do you know what Int Math R B is?

ReplyOptionsI'm not the best at math, but I feel like the bottom half…They values you'd say they'd be don't look correct. Then again, I'm probably wrong.

ReplyOptionsIs this math easy?

ReplyOptionsHey RB! I just want to say that I am 31 years old, and not working at the moment… I have never been to college, and I also still live with my mother and step father. I have had a really hard time growing up and made some big mistakes hanging out with the wrong type of people, and got deep into drugs. But I have been sober since August 13th 2015, and now that I am sober and finally done with going to meetings and everything, it is time that I start my future, because I have waited long enough. So since Comp-Sci has been my passion since I was 11, I have finally decided to learn how to program and make my own apps/programs. Your beginners guides were introduced to me a few days ago in the Unity Official Discord, and ever since… I have been SO happy that I finally found a simple, yet detailed, and comprehensive guide.

I just want to say thank you SO much! I truly feel excited about the future now, and I feel motivated, and I cannot wait to see where this trail leads me!

Thanks again,

Jon

ReplyOptionsSorry for not replying sooner. (It says "guest" by your name, and I think that likely means you won't even see this reply, unfortunately.) But I'm very happy to hear this. I'm glad it's making a difference for you!

ReplyOptions## Post preview:

Close preview