In mathematics, the absolute value or modulus of a real number x, denoted |x|, is the non-negative value of x without regard to its sign. Namely, |x| = x if x is positive, and |x| = −x if x is negative (in which case −x is positive), and |0| = 0. For example, the absolute value of 3 is 3, and the absolute value of −3 is also 3. The absolute value of a number may be thought of as its distance from zero.

To find the absolute value of a number in C#, use the **Math.Abs** method.

**Example 1:**

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
using System; class Program { static void Main() { int val1 = 77; int val2 = -88; Console.WriteLine("Before..."); Console.WriteLine(val1); Console.WriteLine(val2); int abs1 = Math.Abs(val1); int abs2 = Math.Abs(val2); Console.WriteLine("After..."); Console.WriteLine(abs1); Console.WriteLine(abs2); } } |

**Example 2:**

Write a C# program to get the absolute value of the difference between two given numbers. Return double the absolute value of the difference if the first number is greater than second number.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
using System; using System.Collections.Generic; public class Exercise20 { static void Main(string[] args) { Console.WriteLine(result(13, 40)); Console.WriteLine(result(50, 21)); Console.WriteLine(result(0, 23)); } public static int result(int a, int b) { if (a > b) { return (a - b)*2; } return b - a; } } |