Performing Basic Arithmetic Operations with Visual C


Performing Basic Arithmetic Operations with Visual C#

You have to have solid math skills to be a programmer; you'll be performing a lot of basic arithmetic when writing Visual C# applications. To get the results you're looking for in any given calculation, you must

  • Know the mathematical operator that performs the desired arithmetic function

  • Understand and correctly use order of precedence

Using the correct mathematical operator is simple. Most are easy to commit to memory, and you can always look up the ones you're not quite sure of. I'm not going to go into great detail on any of the math functions (if you've made it this far, I'm sure that you have a working grasp of basic math), but I will cover them all.

By the Way

In Hour 15, "Debugging Your Code", you learn about the System.Diagnostics.Debug.WriteLine() method. This method prints text to the Output window and is used in the examples throughout this hour. You will not be asked to create a project in this chapter, but you may want to try some of these examples in a test project. Because you will be using several debug statements, it will be helpful to declare the System.Diagnostics namespace in the header of your class. This permits you to use the methods of the namespace without having to qualify the entire namespace. The following is the line you need to add at the beginning of your class (put it with the other using statements created automatically by Visual C#):

using System.Diagnostics;



Performing Addition

Simple addition is performed using the standard addition symbol, the + character. The following line prints the sum of 4, 5, and 6:

Debug.WriteLine(4 + 5 + 6);


You don't have to use a hard-coded value with arithmetic operators. You can use any of the arithmetic operators on numeric variables and constants. For example:

const int c_FirstValue = 4; const int c_SecondValue = 5; Debug.WriteLine(c_FirstValue + c_SecondValue);


This bit of code prints the sum of the constants c_FirstValue and c_SecondValue, which is 9.

Performing Subtraction and Negation

Like the addition operator, you're probably familiar with the subtraction operator because it's the same one you would use on a calculator or when writing an equation: the character. The following line of code prints 2 (the total of 64):

Debug.WriteLine(6 - 4);


As with written math, the character is also used to denote a negative number. For example, to print the value 6, you would use a statement such as the following:

Debug.WriteLine(-6);


Performing Multiplication

If you work with adding machines, you already know the multiplication operator: the * character. You can enter this character using Shift+8 or by pressing the * key located in the upper row of the keypad section of the keyboard. Although you would ordinarily use a x when writing multiplication equations such as 3 x 2 = 6 on paper, you'll receive an error if you try this in code; you have to use the * character. The following statement prints 20 (5 multiplied by 4):

Debug.WriteLine(5 * 4);


Performing Division

Division is accomplished using the / operator. This operator is easy to remember if you think of division as fractions. For example, one-eighth is written as 1/8, which literally means one divided by eight. The following statement prints 8 (32 divided by 4):

Debug.WriteLine(32 / 4);


Visual C# overloads the division operator. This means that based on the input arguments, the results may vary. For example, Visual C# division will return an integer when dividing integers, but it will return a fractional number if a float, a double, or a decimal data type is used. Hence, 32 / 5 will return 6, dropping the remainder (2, in this case). If you wanted to return the actual value of the operation 32 / 5, you would have to specify the numbers with decimal places (that is, 32.0 / 5.0).

Performing Modulus Arithmetic

Modulus arithmetic is the process of performing division on two numbers but keeping only the remainder. Modulus arithmetic is performed using the % operator, rather that the / symbol. The following are examples of modules statements and the values they would print:

Debug.WriteLine(10 % 5);      // Prints 0 Debug.WriteLine(10 % 3);      // Prints 1 Debug.WriteLine(12 % 4.3);    // Prints 3.4 Debug.WriteLine(13.6 % 5);    // Prints 3.6


The first two statements are relatively easy to understand: 5 goes into 10 twice with no remainder, and 3 goes into 10 three times with a remainder of 1. Visual C# processes the third statement as 4.3 going into 12 two times with a remainder of 3.4. In the last statement, Visual C# performs the modules operation as 5 going into 13.6 twice with a remainder of 3.6.

Determining the Order of Operator Precedence

When several arithmetic operations occur within a single equation (called an expression), Visual C# has to resolve the expression in pieces. The order in which these operations are evaluated is known as operator precedence. To fully understand operator precedence, you have to brush up a bit on your algebra skills (most of the math you perform in code is algebraic).

Consider the following expression:

Debug.WriteLine(6 + 4 * 5);


Two arithmetic operations occur in this single expression. To evaluate the expression, Visual C# has to perform both operations: multiplication and addition. Which operation gets done first? Does it matter? Absolutely! If Visual C# performs the addition before the multiplication, you end up with the following:

Step 1: 6 + 4 = 10

Step 2: 10 * 5 = 50

The final result would be that of Visual C# printing 50. Now look at the same equation with the multiplication performed prior to addition:

Step 1: 4 * 5 = 20

Step 2: 20 + 6 = 26

In this case, Visual C# would print 26a dramatically different number from the one computed when the addition is performed first. To prevent these types of problems, Visual C# consistently performs arithmetic operations in the same orderthe order of operator precedence. Table 12.1 lists the order of operator precedence for arithmetic and Boolean operators. (Boolean operators are discussed later in this hour.) If you're familiar with algebra, you'll note that the order of precedence used by Visual C# is the same as that used in algebraic formulas.

Table 12.1. Visual C# 2005's Order of Operator Precedence

Category

Operators

Multiplicative

* / %

Additive

+ -

Equality

== (equal), != (not equal)

Logical AND

&

Logical XOR

^

Logical OR

|

Conditional AND

&&

Conditional OR

||

Conditional

?:


By the Way

Notice that two equal signs are used to denote equality, not one as you might expect.


All comparison operators such as >, <, and >= (discussed in the next section) have an equal precedence. When operators have an equal precedence, Visual C# evaluates them from left to right. Notice that multiplication and division operators have an equal precedence, so in an expression that has both, the operators would be evaluated from left to right. The same holds true for addition and subtraction. When expressions contain operators from more than one category (arithmetic, comparison, or logical), arithmetic operators are evaluated first, comparison operators are evaluated next, and logical operators are evaluated last.

Just as when writing an equation on paper, you can use parentheses to override the order of operator precedence. Operations placed within parentheses are always evaluated first. Consider the previous example:

Debug.WriteLine(6 * 5 + 4);


Using the order of operator precedence, Visual C# evaluates the equation like this:

Debug.WriteLine((6 * 5) + 4);


The multiplication is performed first, and then the addition. If you want the addition performed prior to the multiplication, you could write the statement like this:

Debug.WriteLine(6 * (5 + 4));


By the Way

When writing complex expressions, you have to be conscious of the order of operator precedence and use parentheses to override the default precedence when necessary. Personally, I try to always use parentheses so that I'm sure of what's happening and my code is easier to read.





Sams Teach Yourself Microsoft Visual C# 2005 in 24 Hours, Complete Starter Kit
Sams Teach Yourself Visual C# 2005 in 24 Hours, Complete Starter Kit
ISBN: 0672327406
EAN: 2147483647
Year: N/A
Pages: 248
Authors: James Foxall

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net