Home C# Arithmetic operators in C# tutorial

Arithmetic operators in C# tutorial

Arithmetic operators in C# are used to perform mathematical operations on numeric values.

These include basic operations like addition, subtraction, multiplication, division, and modulus. In this tutorial, we’ll cover:

Let’s dive into each topic with examples.

1. Basic Arithmetic Operators

C# has five basic arithmetic operators:

Operator Description
+ Addition
Subtraction
* Multiplication
/ Division
% Modulus (Remainder)

Example:

using System;

public class BasicArithmeticOperators
{
    public static void Main()
    {
        int a = 10;
        int b = 3;

        Console.WriteLine("Addition: " + (a + b));         // 13
        Console.WriteLine("Subtraction: " + (a - b));      // 7
        Console.WriteLine("Multiplication: " + (a * b));   // 30
        Console.WriteLine("Division: " + (a / b));         // 3
        Console.WriteLine("Modulus: " + (a % b));          // 1
    }
}

In this example:

  • Addition, subtraction, multiplication, and division are straightforward.
  • Modulus returns the remainder of the division, which is 1 in 10 % 3.

Note on Division: When dividing integers in C#, the result is also an integer (any decimal part is discarded). To get a decimal result, one of the numbers must be a float or double.

2. Compound Assignment Operators

Compound assignment operators combine an arithmetic operation with assignment, making the code more concise.

Operator Description Example
+= Addition a += b
-= Subtraction a -= b
*= Multiplication a *= b
/= Division a /= b
%= Modulus a %= b

Example:

using System;

public class CompoundAssignment
{
    public static void Main()
    {
        int a = 10;

        a += 5;   // Same as a = a + 5;
        Console.WriteLine("a += 5: " + a);  // 15

        a -= 3;   // Same as a = a - 3;
        Console.WriteLine("a -= 3: " + a);  // 12

        a *= 2;   // Same as a = a * 2;
        Console.WriteLine("a *= 2: " + a);  // 24

        a /= 4;   // Same as a = a / 4;
        Console.WriteLine("a /= 4: " + a);  // 6

        a %= 5;   // Same as a = a % 5;
        Console.WriteLine("a %= 5: " + a);  // 1
    }
}

Compound assignment operators make the code more concise and are often used in loops and calculations where a variable’s value is updated repeatedly.

3. Increment and Decrement Operators

C# provides special operators to increase or decrease a value by 1:

Operator Description
++ Increment by 1
Decrement by 1

These operators can be used in prefix (++a) or postfix (a++) form:

  • Prefix (++a or –a): Increments or decrements the value before it’s used in an expression.
  • Postfix (a++ or a–): Uses the current value in the expression first, then increments or decrements.

Example:

using System;

public class IncrementDecrement
{
    public static void Main()
    {
        int x = 5;
        
        Console.WriteLine("x: " + x);        // 5
        Console.WriteLine("x++: " + x++);    // 5 (Post-increment: value shown before increment)
        Console.WriteLine("After x++: " + x); // 6

        Console.WriteLine("++x: " + ++x);    // 7 (Pre-increment: value shown after increment)
        Console.WriteLine("x--: " + x--);    // 7 (Post-decrement: value shown before decrement)
        Console.WriteLine("After x--: " + x); // 6
    }
}

4. Order of Operations (Precedence)

When multiple operators are used, C# follows a specific order of precedence. The order of operations is similar to PEMDAS in mathematics:

  1. Parentheses
  2. Multiplication (*), Division (/), and Modulus (%)
  3. Addition (+) and Subtraction (-)

Example:

using System;

public class OperatorPrecedence
{
    public static void Main()
    {
        int result1 = 10 + 5 * 2; // Multiplication first: 10 + (5 * 2) = 20
        int result2 = (10 + 5) * 2; // Parentheses first: (10 + 5) * 2 = 30

        Console.WriteLine("10 + 5 * 2 = " + result1);  // 20
        Console.WriteLine("(10 + 5) * 2 = " + result2); // 30
    }
}

In this example:

  • Without parentheses, multiplication takes precedence over addition.
  • Adding parentheses changes the order, so addition happens before multiplication.

5. Examples with Arithmetic Operators

Let’s explore practical examples where arithmetic operators come in handy.

Example 1: Calculating Area of a Circle

using System;

public class CircleArea
{
    public static void Main()
    {
        double radius = 5.0;
        double pi = 3.14159;
        double area = pi * radius * radius;

        Console.WriteLine("Area of the circle: " + area);
    }
}

Here, we use multiplication to calculate the area of a circle, given the radius and the constant value of π (pi).

Example 2: Converting Seconds to Minutes and Seconds

using System;

public class TimeConversion
{
    public static void Main()
    {
        int totalSeconds = 500;

        int minutes = totalSeconds / 60;
        int seconds = totalSeconds % 60;

        Console.WriteLine("Total Time: " + minutes + " minutes and " + seconds + " seconds.");
    }
}

In this example:

  • Division (/) calculates the number of full minutes.
  • Modulus (%) calculates the remaining seconds after converting to minutes.

Output:

Total Time: 8 minutes and 20 seconds.

Example 3: Calculating Average of an Array

using System;

public class AverageCalculator
{
    public static void Main()
    {
        int[] scores = { 85, 90, 78, 92, 88 };
        int sum = 0;

        for (int i = 0; i < scores.Length; i++)
        {
            sum += scores[i];
        }

        double average = (double)sum / scores.Length;
        Console.WriteLine("Average score: " + average);
    }
}

Here:

  • We use a for loop and the += operator to sum all the elements in the scores array.
  • We cast sum to double to ensure decimal precision in the average calculation.

Summary

In C#, arithmetic operators are essential for performing basic mathematical calculations and are widely used in various types of applications. Here’s a quick recap:

  • Basic Arithmetic Operators: Perform addition, subtraction, multiplication, division, and modulus operations.
  • Compound Assignment Operators: Combine arithmetic operations with assignment, e.g., +=, -=.
  • Increment and Decrement Operators: Increase or decrease values by 1 with ++ and –.
  • Operator Precedence: Controls the order of operations; use parentheses to clarify calculations.
  • Practical Applications: Use arithmetic operators for tasks like calculating areas, converting units, and finding averages.

 

You may also like