C# Arithmetic Operators

Arithmetic operators in C# are used to perform mathematical calculations like Addition, Subtraction, Multiplication, Division, and Modulus. Basically, these C# Arithmetic operators work on two operands. Hence these are called binary operators.

Let us see an example to clearly understand them. The below table shows the list of available C# Arithmetic operators and explains their operations.

C# Arithmetic OperatorsOperationExample
+Addition3 + 2 = 5
Subtraction3 – 2 = 1
*Multiplication3 * 2 = 6
/Division3 / 2 = 1
%Modulus3 % 2 = 1

C# Arithmetic Operators Example

In the following C# example, we are using an integer variable x and double variable y as two operands of the operator and performing arithmetic operations on them.

When applying division/operator, we must keep in mind the following points.

  1. The division of any number by zero gives an application error. Ex: x/0
  2. By default, the result will always round to its nearest whole number. Ex: 11/2 gives 5.
  3. Variables must be of the same data type (int-int, double-double, etc.) unless they can implicitly convert. In Implicit conversion, the System allows conversion in type-safe, and no data can be lost.
  4. If we want the accurate value of division, for ex: 3/2 = 1.5, where 3 and 2 are integer values, we have to typecast the result to float type explicitly.
using System;

class Arithmetic_Operations
{
    static void Main()
    {
        int x = 10;
        int y = 8;
        int add, sub, multi, div_int, modulus;
        float div_float;

        add = x+y;
        Console.WriteLine("{0} + {1} = {2}", x, y, add);

        sub = x-y;
        Console.WriteLine("{0} - {1} = {2}", x, y, sub);

        multi = x*y;
        Console.WriteLine("{0} * {1} = {2}", x, y, multi);

        div_int = x/y;
        Console.WriteLine("{0} / {1} = {2}", x, y, div_int);

        div_float = (float)x/y;
        Console.WriteLine("{0} / {1} = {2}", x, y, div_float);

        modulus = x%y;
        Console.WriteLine("{0} % {1} = {2}", x, y, modulus);
    }
}
C# Arithmetic Operators 1

ANALYSIS

In the above example, integer variables x and y are the two operands on which we are applying arithmetic operators(+, -, *, /, %).

Coming to the accurate value of 10/8, we have explicitly converted to type float and stored the C# result in a float variable div_float.

Categories C#