
.NET 1.1+C# Arithmetic Operators
The sixth part of the C# Fundamentals tutorial describes the basic arithmetic operators available to the C# programmer. These operators allow general algebraic operations to be carried out against numeric data type values.
Outputting Numeric Values
Before we begin the examination of the arithmetic operators we will take a brief aside. So far in the C# Fundamentals tutorial there has been no discussion of outputting numeric values to the screen. As we start changing variable values, we need to be able to view the results of the operations.
In the first part of the C# Fundamentals tutorial, we created a console application and outputted text using the Console.WriteLine command. This may also be used to output numeric data. For example:
int quantity = 5;
Console.WriteLine(quantity); // Outputs 5
You can use the Console.WriteLine command to test the examples in the following sections.
Basic Arithmetic Operators
There are five basic arithmetic operators available in C#. These are used for addition (+), subtraction (-), multiplication (*), division (/) and modulus (%). Of these, the first four are available to almost every programming language. Here are some simple examples:
int a = 6;
int b = 3;
int result;
result = a + b; // result = 9
result = a - b; // result = 3
result = a * b; // result = 18
result = a / b; // result = 2
result = a + b - 1; // result = 8
It is important to remember that the resultant value of a mathematical operation is subject to the rules of the receiving variable's data type. The result of a division operation may yield a floating point value. However, if assigned to an integer the fractional part will be lost. Equally important, and less obvious, is the effect of an operation performed on several integers and assigned to a non-integer. In this case, the result is calculated as an integer before being implicitly converted. This means that although the resultant value is assigned to a floating point variable, the fractional part is still truncated unless at least one of the values is explicitly converted first. The following examples illustrate this:
int a = 7;
int b = 3;
int integerResult;
float floatResult;
integerResult = a / b; // integerResult = 2 (truncated)
floatResult = a / b; // floatResult = 2.0 (truncated)
floatResult = (float)a / b; // floatResult = 2.33333325
The last of the five arithmetic operators is modulus. This operator yields a value equal to the remainder of an integer division. For example, when ten is divided by three the answer is three and the remainder is one. The modulus operator can be used with all numeric data types.
int a = 10;
int b = 3;
float c = 3.5F;
int integerResult;
float floatResult;
integerResult = a % b; // integerResult = 1
floatResult = a % b; // floatResult = 1.0
floatResult = a % c; // floatResult = 3.0
19 August 2006