Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Natural Numbers
  • Whole Numbers
  • Real Numbers
  • Integers
  • Rational Numbers
  • Irrational Numbers
  • Complex Numbers
  • Prime Numbers
  • Odd Numbers
  • Even Numbers
  • Properties of Numbers
  • Number System
Open In App
Next Article:
C Program to Check Whether a Number is Positive or Negative or Zero
Next article icon

Program to find absolute value of a given number

Last Updated : 13 Dec, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an integer N, The task is to find the absolute value of the given integer.

Examples: 

Input: N = -6 
Output: 6
Explanation: The absolute value of -6 is 6 which is non negative

Input: N = 12 
Output: 12 

Naive Approach: To solve the problem follow the below idea:

The absolute value of any number is always positive. For any positive number, the absolute value is the number itself and for any negative number, the absolute value is (-1) multiplied by the negative number

Learn More, Positive and Negative Numbers

Below is the implementation of the above approach.

C++

// C++ program for Method 1
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the absolute value
void findAbsolute(int N)
{
  
    // If the number is less than
    // zero, then multiply by (-1)
    if (N < 0) 
    {
        N = (-1) * N;
    }
  
    // Print the absolute value
    cout << " " << N;
}
  
// Driver Code
int main()
{
  
    // Given integer
    int N = -12;
  
    // Function call
    findAbsolute(N);
    return 0;
}
  
// This code is contributed by shivanisinghss2110
                      
                       

C

// C program for Method 1
#include <stdio.h>
  
// Function to find the absolute value
void findAbsolute(int N)
{
  
    // If the number is less than
    // zero, then multiply by (-1)
    if (N < 0) {
        N = (-1) * N;
    }
  
    // Print the absolute value
    printf("%d ", N);
}
  
// Driver Code
int main()
{
  
    // Given integer
    int N = -12;
  
    // Function call
    findAbsolute(N);
    return 0;
}
                      
                       

Java

// Java program for Method 1
class GFG{
      
// Function to find the absolute value
static void findAbsolute(int N)
{
  
    // If the number is less than
    // zero, then multiply by (-1)
    if (N < 0) 
    {
        N = (-1) * N;
    }
  
    // Print the absolute value
    System.out.printf("%d ", N);
}
  
// Driver Code
public static void main(String[] args)
{
  
    // Given integer
    int N = -12;
  
    // Function call
    findAbsolute(N);
}
}
  
// This code is contributed by 29AjayKumar
                      
                       

Python3

# Python3 program for Method 1
  
# Function to find the absolute value
def findAbsolute(N):
  
    # If the number is less than
    # zero, then multiply by (-1)
    if (N < 0):
        N = (-1) * N;
      
    # Print the absolute value
    print(N);
  
# Driver code
if __name__ == '__main__':
  
    # Given integer
    N = -12;
  
    # Function call
    findAbsolute(N);
  
# This is code contributed by amal kumar choubey
                      
                       

C#

// C# program for Method 1
using System;
using System.Collections.Generic;
  
class GFG{
      
// Function to find the absolute value
static void findAbsolute(int N)
{
  
    // If the number is less than
    // zero, then multiply by (-1)
    if (N < 0) 
    {
        N = (-1) * N;
    }
  
    // Print the absolute value
    Console.Write("{0} ", N);
}
  
// Driver Code
public static void Main(String[] args)
{
  
    // Given integer
    int N = -12;
  
    // Function call
    findAbsolute(N);
}
}
  
// This code is contributed by sapnasingh4991
                      
                       

Javascript

<script>
    // Javascript program for Method 1 
      
    // Function to find the absolute value 
    function findAbsolute(N) 
    { 
  
        // If the number is less than 
        // zero, then multiply by (-1) 
        if (N < 0)  
        { 
            N = (-1) * N; 
        } 
  
        // Print the absolute value 
        document.write(" " + N); 
    } 
  
      
    // Given integer 
    let N = -12; 
    
    // Function call 
    findAbsolute(N); 
      
    // This code is contributed by suresh07.
</script>
                      
                       

Output
 12

Time Complexity: O(1)
Auxiliary Space: O(1)

Find the absolute value of a given number Using Bitmasking: 

To solve the problem follow the below idea:

Negative numbers are stored in the form of 2s complement, to get the absolute value we have to toggle bits of the number and add 1 to the result. 

Follow the steps below to implement the idea: 

  • Set the mask as right shift of the integer by 31 (assuming integers are stored using 32 bits) mask = n >> 31
  • For negative numbers, above step sets mask as 1 1 1 1 1 1 1 1 and 0 0 0 0 0 0 0 0 for positive numbers. Add the mask to the given number i.e. mask + n   
  • XOR of mask + n and mask gives the absolute value i.e. [Tex](mask + n)^mask  [/Tex]  

Below is the implementation of the above approach.

C++

// C++ program for above approach
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the absolute
// value
void findAbsolute(int N)
{
  
    // Find mask
    int mask = N >> (sizeof(int) * CHAR_BIT - 1);
  
    // Print the absolute value
    // by (mask + N)^mask
    cout << ((mask + N) ^ mask);
}
  
// Driver Code
int main()
{
  
    // Given integer
    int N = -12;
  
    // Function call
    findAbsolute(N);
    return 0;
}
  
// This code is contributed by Code_Mech
                      
                       

C

// C program for Method 2
#include <stdio.h>
#define CHAR_BIT 8
  
// Function to find the absolute
// value
void findAbsolute(int N)
{
  
    // Find mask
    int mask
        = N
          >> (sizeof(int) * CHAR_BIT - 1);
  
    // Print the absolute value
    // by (mask + N)^mask
    printf("%d ", (mask + N) ^ mask);
}
  
// Driver Code
int main()
{
  
    // Given integer
    int N = -12;
  
    // Function call
    findAbsolute(N);
    return 0;
}
                      
                       

Java

// Java program for Method 2
class GFG{
      
static final int CHAR_BIT = 8;
  
// Function to find the absolute value
static void findAbsolute(int N)
{
  
    // Find mask
    int mask = N >> (Integer.SIZE / 8 *
                         CHAR_BIT - 1);
  
    // Print the absolute value
    // by (mask + N)^mask
    System.out.printf("%d ", (mask + N) ^ mask);
}
  
// Driver Code
public static void main(String[] args)
{
  
    // Given integer
    int N = -12;
  
    // Function call
    findAbsolute(N);
}
}
  
// This code is contributed by 29AjayKumar
                      
                       

Python3

# Python3 program for Method 2
import sys
  
CHAR_BIT = 8;
  
# Function to find the absolute value
def findAbsolute(N):
      
    # Find mask
    mask = N >> (sys.getsizeof(int()) // 8 * 
                              CHAR_BIT - 1);
  
    # Print the absolute value
    # by (mask + N)^mask
    print((mask + N) ^ mask);
  
# Driver Code
if __name__ == '__main__':
      
    # Given integer
    N = -12;
  
    # Function call
    findAbsolute(N);
  
# This code is contributed by 29AjayKumar
                      
                       

C#

// C# program for Method 2
using System;
  
class GFG{
      
static readonly int CHAR_BIT = 8;
  
// Function to find the absolute value
static void findAbsolute(int N)
{
      
    // Find mask
    int mask = N >> (sizeof(int) / 8 *
                        CHAR_BIT - 1);
  
    // Print the absolute value
    // by (mask + N)^mask
    Console.Write((mask + N) ^ mask);
}
  
// Driver Code
public static void Main(String[] args)
{
  
    // Given integer
    int N = -12;
  
    // Function call
    findAbsolute(N);
}
}
  
// This code is contributed by 29AjayKumar
                      
                       

Javascript

<script>
    // Javascript program for Method 2
      
    let CHAR_BIT = 8;
   
    // Function to find the absolute value
    function findAbsolute(N)
    {
  
        // Find mask
        let mask = N >> (4 / 8 * CHAR_BIT - 1);
  
        // Print the absolute value
        // by (mask + N)^mask
        document.write((mask + N) ^ mask);
    }
      
    // Given integer
    let N = -12;
   
    // Function call
    findAbsolute(N);
  
// This code is contributed by mukesh07.
</script>
                      
                       

Output
12

Time Complexity: O(1)
Auxiliary Space: O(1)

Find the absolute value of a given number Using the inbuilt abs() function:

To solve the problem follow the below idea:

The inbuilt function abs() in stdlib.h library finds the absolute value of any number. This can be used to find absolute value of any integer.

Below is the implementation of the above approach: 

C++

// C++ program for Method 3
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the absolute
// value
void findAbsolute(int N)
{
  
    // Find absolute
    int X = abs(N);
  
    // Print the absolute value
    cout << X;
}
  
// Driver Code
int main()
{
  
    // Given integer
    int N = -12;
  
    // Function call
    findAbsolute(N);
    return 0;
}
  
// This code is contributed by Nidhi_biet
                      
                       

C

// C program for Method 3
  
#include <stdio.h>
#include <stdlib.h>
  
// Function to find the absolute
// value
void findAbsolute(int N)
{
  
    // Find absolute
    int X = abs(N);
  
    // Print the absolute value
    printf("%d ", X);
}
  
// Driver Code
int main()
{
  
    // Given integer
    int N = -12;
  
    // Function call
    findAbsolute(N);
    return 0;
}
                      
                       

Java

// Java program for Method 3
class GFG{
      
// Function to find the absolute
// value
static void findAbsolute(int N)
{
  
    // Find absolute
    int X = Math.abs(N);
  
    // Print the absolute value
    System.out.printf("%d", X);
}
  
// Driver Code
public static void main(String[] args)
{
  
    // Given integer
    int N = -12;
  
    // Function call
    findAbsolute(N);
}
}
  
// This code is contributed by sapnasingh4991
                      
                       

Python3

# Python3 program for Method 3
import math
  
# Function to find the absolute
# value
def findAbsolute(N):
  
    # Find absolute
    X = abs(N);
  
    # Print the absolute value
    print(X);
  
# Driver Code
  
# Given integer
N = -12;
  
# Function call
findAbsolute(N);
  
# This code is contributed by Nidhi_biet
                      
                       

C#

// C# program for Method 3
using System;
  
class GFG{
      
// Function to find the absolute
// value
static void findAbsolute(int N)
{
  
    // Find absolute
    int X = Math.Abs(N);
  
    // Print the absolute value
    Console.Write("{0}", X);
}
  
// Driver Code
public static void Main(String[] args)
{
  
    // Given integer
    int N = -12;
  
    // Function call
    findAbsolute(N);
}
}
  
// This code is contributed by 29AjayKumar
                      
                       

Javascript

<script>
    // Javascript program for Method 3
      
    // Function to find the absolute
    // value
    function findAbsolute(N)
    {
  
        // Find absolute
        let X = Math.abs(N);
  
        // Print the absolute value
        document.write(X);
    }
      
    // Given integer
    let N = -12;
   
    // Function call
    findAbsolute(N);
  
</script>
                      
                       

Output
12

Time Complexity: O(1)
Auxiliary Space: O(1)



Next Article
C Program to Check Whether a Number is Positive or Negative or Zero

G

geeksforgeeks user
Improve
Article Tags :
  • C Programs
  • C# Programs
  • C++ Programs
  • DSA
  • Java Programs
  • Mathematical
  • PHP Programs
  • School Programming
  • Numbers
Practice Tags :
  • Mathematical
  • Numbers

Similar Reads

  • Java Program to Check if all digits of a number divide it
    Given a number n, find whether all digits of n divide it or not.Examples: Input : 128 Output : Yes 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0. Input : 130 Output : No We want to test whether each digit is non-zero and divides the number. For example, with 128, we want to test d != 0 && 128
    2 min read
  • C Program to Check for Odd or Even Number
    Write a C program to check whether the given number is an odd number or an even number. A number that is completely divisible by 2 is an even number and a number that is not completely divisible by 2 leaving a non-zero remainder is an odd number. Example Input: N = 4Output: EvenExplanation: 4 is div
    4 min read
  • C Program to Check Whether a Number is Positive or Negative or Zero
    Write a C program to check whether a given number is positive, negative, or zero. Examples Input: 10Output: PositiveExplanation: Since 10 is greater than 0, it is positive. Input: -5Output: NegativeExplanation: Since -5 is less than 0, it is negative. Different Ways to Check for Positive Numbers, Ne
    3 min read
  • How to Find the Range of Numbers in an Array in C?
    The range of numbers within an array is defined as the difference between the maximum and the minimum element present in the array. In this article, we will learn how we can find the range of numbers in an array in C. Example Input:int arr[] = { 23, 12, 45, 20, 90, 89, 95, 32, 65, 19 }Output: The ra
    2 min read
  • Reverse Number Program in C
    The reverse of a number means reversing the order of digits of a number. In this article, we will learn how to reverse the digits of a number in C programming language. For example, if number num = 12548, the reverse of number num is 84521. Algorithm to Reverse an IntegerInput: num (1) Initialize re
    2 min read
  • C++ program for Complex Number Calculator
    Pre-Requisites: Complex Numbers, Mathematics, Object-oriented Programming This is a Complex Number Calculator which performs a lot of operations which are mentioned below, to simplify our day-to-day problems in mathematics. The implementation of this calculator is done using C++ Programming Language
    15+ min read
  • Maximize removal of adjacent array elements based on their absolute value
    Given an array arr[] of positive and negative integers, the task is to print the array after the removal of adjacent array elements starting from the last index of the array.Array elements can be removed based on the following conditions: Two adjacent elements of opposite sign needs to be compared o
    8 min read
  • Program that allows integer input only
    Given an input value N, the task is to allow taking only integer input from the user. Now, if the user enters any input other than an integer, that is, a character or symbol, it will not be accepted by the program. Below is the C program to implement this approach: [GFGTABS] C // C program for the a
    3 min read
  • TCS Coding Practice Question | Sum of Digits of a number
    Given a number, the task is to find the Sum of Digits of this number using Command Line Arguments. Examples: Input: num = 687 Output: 21 Input: num = 12 Output: 3 Approach: Since the number is entered as Command line Argument, there is no need for a dedicated input lineExtract the input number from
    4 min read
  • C++ Program to Perform Calculations in Pure Strings
    Given a string of operations containing three operands for each operation "type of command", "first operand", and "second operand". Calculate all the commands given in this string format. In other words, you will be given a pure string that will ask you to perform an operation and you have to perfor
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences