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

Here, we are going to learn how to print the absolute value of a number without using Math.Abs() method in C#?
Submitted by Nidhi, on October 09, 2020

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.

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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.