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.
Program:
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.
Output:
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.