C# Tutorial Part 4.0 – Operators

The support vote symbol redrawn in the SVG format.

Image via Wikipedia

This is the fourth main part of my C# tutorial, and the topic this time will be operators.
By operators I mean things that can be used to change a variables value, and this lesson will focus on things like +, -, *, / and !.

If you have been playing around with variables you will know that numerical ones can be added together and subtracted. Here is an example of this:

int number1 = 10, number2 = 20, answer=0;
answer = number1 + number2;
Console.WriteLine(answer);
Console.WriteLine(answer-number1-number2);

Note: Short sections of code I use in tutorials will not work on their own, you must set up a class and a static Main method like in the early tutorials, and also remember to type ‘using system;’ (without the quotes) to make sure Console.WriteLine works

As you can see, the first line declares and initialises three integer variables, as shown in lesson 3.
The second line uses the assignment operator (the = sign) to assign the value of whatever was on its right into the variable ‘answer’ on its left. In this case, on its right was the expression ‘number1 + number2’, so it worked out the answer to the expression and gave ‘answer’ that value.
The third line simply prints the value of answer to the screen using Console.WriteLine. Previously we have written things like:
Console.WriteLine(“The value of answer is: {0}”, answer);
This is good for putting some text to explain the number you are printing, and is explained in the first part of the tutorial, but when you just need to print a variable’s value on its’ own, you can use it as the only parameter.
The fourth line prints the value of the expression ‘answer-number1-number2’, which was zero.

List of basic numerical C# operators:

Binary – (Use two variables)
+       Add
–        Subtract
*       Multiply
/       Divide
%      Remainder – Gives the remainder of the division of two numbers eg. answer = number1%number2;
=       Assignment operator – You should already know what it does

Flipping
!     Logical Negation Operator – Works with true/false statements (such as boolean variables) and switches them from true to false or vice versa. Actually this isn’t numerical, it’s logical
~     Bitwise Not Operator – Flips over binary digits turning binary 1s into 0s and vice versa

Increment/Decrement
++                            Increment (Increase by 1)
– –                               Decrement (Decrease by 1)
<variable>++     Post-increment
++<variable>     Pre-increment
<variable>- –       Post-decrement
– -<variable>       Pre-decrement
(Where <variable> is a variable of a numerical type, such as int)

Now, how to use them:

Remainder

+, -, * and / are all pretty simple – they are all used as above.
% is a bit more confusing, though.
Say I had two variables:

int number1 = 3, number2 = 10, answer = 0; //Declarations and initialisations
answer = number2%number1;
Console.Write(“The remainder of 10 divided by 3 is: “);
Console.WriteLine(answer);

On line two, answer is given the value of the remainder of the division number2/number1
It is then printed to the screen.
If you want to, stick a Console.ReadLine(); on the end so it stays long enough for you to read the answer and try it out.
The output will be the number 1, since 3 goes into 10 three times, with 1 left over.
The process the computer thinks through (translated into human thought) may be something like this:
1*3=3    2*3=6    3*3=9    4*3=12    Oops, too high! Go back one:     3*3=9    10-9=1     3 fits into 10 3 times, with a remainder of 1!

Quick calculations

A quick way of doing some calculations works like this:

int number1 = 2, number2 = 3;
number1+=number2;
Console.WriteLine(“Answer: {0}”,number1);

In this program, two variables, number1 and number2 are declared and initialized with values, then on the second line, number1 is given a new value, before being printed to the screen.
If you try it out, the answer will be 5.
This is because ‘number1+=number2’ is only a quick way of saying ‘number1 = number1 + number2’. Try it out with different values for the variables until you fully understand. It also works for subtracting, multiplying and dividing. Try it.

Powers (and OOP)

If you were wondering how to work out powers (3 to the power of 5, for instance), there is no simple way to do this. C# does not have a power operator because most programs do not require it. It is possible to work out powers though, by calling the Math.Pow method.
Pow is a method in the Math class, just as WriteLine is a method in the Console class. Math and Console are both in the System namespace. This way of organising your code is called OOP, object orientated programming and is an important concept of programming in C#, but don’t worry if you don’t understand it – you don’t need to at the moment.
To use Pow, you need to send it two numbers to work with and, in return, it will send you the result.
Here’s how you use it:

double number1 = 3.0, number2 = 2.0, answer = 0.0; //Declarations and initialisations
answer = Math.Pow(number1,number2);

This is called calling a method

The values in the brackets are called parameters. They are passed to the function so it can do its job. In this case, we sent the numbers we needed to perform the operation on. Pow contains some code which works out the answer and returns the value. Putting ‘answer =’ before the call means the value Pow returns to us is put into the answer variable using the assignment operator.

Because Math is in the System namespace, you can only use it like that if you have put ‘using System;’ at the beginning of the program, telling the compiler that you will be using classes inside System. You should already have put this if you want to use the class, Console, though. If you only need to use things inside the System namespace once (although I doubt that will be the case) you can avoid having to write ‘using System;’ and just write ‘System.Console.WriteLine’ to call WriteLine, or ‘System.Math.Pow’ to call Pow.

If you understand that, excellent!
Else, don’t worry – you won’t need to for a while.

In Part 4.1, we will continue to look at the different operators and how to use them, before looking at if statements in Part 5.0

Advertisements

About Matt

I like writing, filmmaking, programming and gaming, and prefer creating media to consuming it. On the topic of consumption, I'm also a big fan of eating.
This entry was posted in Programming and tagged , , , , , , , , , , , , , , . Bookmark the permalink.

Enter comment:

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s