Wednesday, February 23, 2011

Basic Calculations

Everyone has a calculator nowadays. There's probably a calculator on your computer right now. If you don't then it won't be hard to make a basic calculator yourself, but before you do that you'll need to know how to add, extract, multiply and divide in C#.

First create a new console application called "BasicCalculations".


Start by typing:
int outcomeByAdding = 5 + 5;
Console.Write(outcomeByAdding);
Console.Read();
The variable "outcomeByAdding" will hold the number 10 after calculating 5 + 5. You put the variable "outcomeByAdding" as the parameter for the "Write" method, so you will see 10 on your screen when running your application by pressing F5 on your keyboard.


You can do the same for subtracting, multiplying and dividing. Add the following to your code below "int outcomeByAdding = 5 + 5;":
int outcomeBySubtracting = 10 - 5;
int outcomeByMultiplying = 5 * 2;
int outcomeByDividing = 10 / 2;

Console.Write(outcomeBySubtracting + "\n");
Console.Write(outcomeByMultiplying + "\n");
Console.Write(outcomeByDividing + "\n");
Putting "outcomeBySubtracting + "\n"" will combine those two. If "\n" was of the basic data type int, then it would add those two numbers. In this case one of the two data is of the basic data type string, so it will combine the two data. "\n" means "new line" and that will make your console application start on a new line. Run your application now and you should see the outcome of all the four calculations.


If you want to add the number 12 to the variable "outcomeByAdding", so it will hold the number 17 won't suffice by typing: "outcomeByAdding + 12;". You will have to type "outcomeByAdding = outcomeByAdding + 12;" below "int outcomeByAdding = 5 + 5;".


Your application will first add the number 10 (the number assigned to your variable) to the number 12 and then assign the number 22 to your variable "outcomeByAdding". You will now see the number 22 instead of the number 10 when you run your application. Instead of typing "outcomeByAdding = outcomeByAdding + 12;" you can also type "outcomeByAdding += 12;". It does the exact same thing, but the full presentation was needed for the explanation. The same can be done with "*", "/" and "-".


Incrementing can be done by putting two "+" signs before or after a variable. For example the variable "outcomeByAdding" will look like "outcomeByAdding++;". Incrementing by typing "outcomeByAdding++;" is the same as "outcomeByAdding = outcomeByAdding + 1;". This will assign the number 23 (22 + 1) to the variable "outcomeByAdding". Decrementing is also a possibility by typing "outcomeByAdding--;" which is the same as "outcomeByAdding = outcomeByAdding - 1;". No, "outcomeByAdding**" or "outcomeByAdding//" won't work.

That's it, basic calculations. You should memorise that calculations are done first and the outcome assigned to the variable.

Source Code BasicCalculations Project

>> If Else Statements

No comments:

Post a Comment