Math

Lesson 7
Author : Afrixi
Last Updated : February, 2023
C# - Programming Language
This course covers the basics of programming in C#.

In C#, you can perform mathematical operations using built-in operators and functions. Here are some important things to know about math in C#:

Basic arithmetic operators: You can use the standard arithmetic operators to perform addition (+), subtraction (-), multiplication (*), and division (/). For example: int result = 3 + 4 * 2 - 6 / 3; will result in 9.

Modulus operator

You can use the modulus operator (%) to get the remainder of a division operation. For example: int remainder = 17 % 5; will result in 2.

Math functions

C# provides a number of math functions in the Math class, such as Math.Sqrt(), Math.Pow(), Math.Abs(), Math.Round(), and Math.Max(). These functions can be used to perform tasks like calculating square roots, raising a number to a power, taking the absolute value of a number, rounding a number to a specified number of decimal places, and finding the maximum of two values.

Order of operations

Like in math, in C# expressions inside parentheses are evaluated first, followed by multiplication and division, and then addition and subtraction. You can use parentheses to control the order of operations.

Here’s an example of how to use some of these math features in C#:

using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            // Basic arithmetic operators
            int result1 = 3 + 4 * 2 - 6 / 3; // 9
            int result2 = (3 + 4) * 2 - 6 / 3; // 10

            // Modulus operator
            int remainder = 17 % 5; // 2

            // Math functions
            double squareRoot = Math.Sqrt(16); // 4
            double power = Math.Pow(2, 3); // 8
            int absoluteValue = Math.Abs(-5); // 5
            double rounded = Math.Round(3.14159, 2); // 3.14
            int max = Math.Max(5, 7); // 7

            // Output values to console
            Console.WriteLine(result1);
            Console.WriteLine(result2);
            Console.WriteLine(remainder);
            Console.WriteLine(squareRoot);
            Console.WriteLine(power);
            Console.WriteLine(absoluteValue);
            Console.WriteLine(rounded);
            Console.WriteLine(max);

            Console.ReadKey();
        }
    }
}

In this example, we’re performing various math operations using arithmetic operators and the Math class functions. We’re outputting the results to the console using Console.WriteLine().