Performing Basic Arithmetic

   

To be a programmer, you have to have solid math skills; you'll be performing a lot of basic arithmetic when writing 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 you have a working grasp of math), but I will cover them all.

graphics/bookpencil.gif

In Hour 7, "Working with Traditional Controls," I mentioned how the System.Diagnostics.Debug.WriteLine() method prints text to the Output window. I use this method 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 we are planning to use 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 C#):

 using System.Diagnostics; 

For more specific information on the Debug object, refer to Hour 16, "Debugging Your Code."

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, in this case, is 9.

Performing Subtraction and Negation

Like the addition operator, you're most likely 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 6 “4):

 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 multiplication character is the asterisk (*) 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 an "x" when writing multiplication equations such as 6 = 3x2 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 slash (/) 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); 

C# overloads the division operator. This means that based on the input arguments, the results may vary. For example, 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).

graphics/bulb.gif

The modulus operator (%) can be used to find the remainder of an integer division.

Performing Modulus Arithmetic

graphics/newterm.gif

Modulus arithmetic is the process of performing division on two numbers but keeping only the remainder. Modulus arithmetic is performed using the % operand, in contrast to using a slash (/) operator symbol. The following are examples of modulus 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. C# processes the third statement as 4.3 going into 12 three times with a remainder of 3.4. In the last statement, C# performs the modulus operation as 5 going into 13.6 twice with a remainder of 3.6.

Determining the Order of Operator Precedence

graphics/newterm.gif

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

Consider the following expression:

 Debug.WriteLine(6 * 5 + 4); 

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

graphics/13equ01.gif


graphics/13equ02.gif


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

graphics/13equ03.gif


graphics/13equ04.gif


In this case, C# would print 54 ”a drastically different number from the one computed when the multiplication is performed first. To prevent these types of errors, C# consistently performs arithmetic operations in the same order ”the order of operator precedence (in this case, multiplication and then addition). Table 13.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 C# is the same as that used in algebraic formulas.

Table 13.1. C#'s Order of Operator Precedence, Highest to Lowest
Category Operators
Multiplicative * / %
Additive + -
Equality == (equal), != (not equal)
Logical AND &
Logical XOR ^
Logical OR
Conditional AND &&
Conditional OR
Conditional ?:
graphics/bookpencil.gif

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

graphics/newterm.gif

All comparison operators (discussed in the next section) have an equal precedence. When operators have an equal precedence, C# evaluates them from left to right. Notice that the 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, C# evaluates the equation like this:

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

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

 Debug.WriteLine(6 * (5 + 4)); 
graphics/bulb.gif

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


   
Top


Sams Teach Yourself C# in 24 Hours
Sams Teach Yourself Visual Basic 2010 in 24 Hours Complete Starter Kit (Sams Teach Yourself -- Hours)
ISBN: 0672331136
EAN: 2147483647
Year: 2002
Pages: 253
Authors: James Foxall

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