C# Arithmetic Operators

In this chapter you will learn:

  1. How to use Arithmetic Operators
  2. Example for C# Arithmetic Operators
  3. How to handle Divide by zero exception

Description

C# defines the following arithmetic operators:

Operator Meaning
+Addition
-Subtraction (also unary minus)
*Multiplication
/ Division
% Modulus
++Increment
-- Decrement

Example

When / is applied to an integer, any remainder will be truncated. For example, 10/3 will equal 3 in integer division.


using System;/*from   w w  w . jav  a2s  .co  m*/

class MainClass
{
    static void Main(string[] args)
    {
        int     a,b,c,d,e,f;

        a = 1;
        b = a + 6;
        Console.WriteLine(b);
        c = b - 3;
        Console.WriteLine(c);
        d = c * 2;
        Console.WriteLine(d);
        e = d / 2;
        Console.WriteLine(e);
        f = e % 2;
        Console.WriteLine(f);
    }
}

The code above generates the following result.

Divide by zero exception

Dividing by zero value generates the DivideByZeroException.


using System;//from  ww w.ja  va2s . c  o  m

class Program
{
    static void Main(string[] args)
    {
        int i = 4;
        int y = 0;
        
        int result = i / y;
        Console.WriteLine("result="+result);


    }
}

The output:

Next chapter...

What you will learn in the next chapter:

  1. What are the assignment operator
  2. Example to use the assignment operators
Home »
  C# Tutorial »
    C# Language »
      C# Operators
C# Arithmetic Operators
C# Arithmetic Assignment Operator
C# Increment and Decrement Operators
C# Remainder operator
C# Relational operators
C# Conditional Operators
C# Ternary operator(The ? Operator)
C# Bitwise Operators
C# Bitwise Shift Operators
C# sizeof Operator
C# typeof Operator