C# - Find the Absolute Value Without Using Math.Abs()

Here, we are going to learn how to print the absolute value of a number without using Math.Abs() method in C#? By Nidhi Last updated : April 15, 2023

Here we will print the absolute value of a number using a user-defined method; if we find the absolute value of a number then we remove the sign of a negative number.

C# program to find the absolute value of a number without using Math.Abs() method

The source code to find the absolute value of a number without using Math.Abs() method is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to print the absolute value of 
//a number without using Math.Abs() method.

using System;
 
class Demo
{
    static int GetAbsoluteValue(int number)
    {
        if (number < 0)
            number = number * -1;
        
        return number;
    }
    
    static void Main()
    {
        int number=0;

        Console.Write("Enter the value of number to find absolute value: ");
        number = int.Parse(Console.ReadLine());

        Console.WriteLine("Absolute value : " + GetAbsoluteValue(number));
    }
}

Output

Enter the value of number to find absolute value: -4
Absolute value : 4
Press any key to continue . . .

Explanation

Here, we created a class Demo that contains two static methods GetAbsolutValue() and Main() method. The GetAbsoluteValue() is used to find the absolute value by removing the minus sign from negative numbers.

In the Main() method, create a local variable number initialized with 0, and read the value of the number and passed to the GetAbsoluteValue() that return absolute value. After that, we printed the absolute value on the consoles screen.

C# Basic Programs »


Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.