Q:

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

belongs to collection: C# Basic Programs | basics

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

//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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# Basic Programs | basics

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C# program to find the Least Common Multiple of tw... >>
<< C# program to find the root of a quadratic equatio...