Absolute value of a number

In number line, the distance between number and origin is called absolute value of a number.




Number line

Number line

Absolute value of negative numbers

Absolute value of -5

Absolute value of positive numbers

Absolute value of 4

Since it is absolute value is a distance, it never be a negative value.

It is always positive.




Algorithm

Let’s take N,

If N is negative, return -N (minus of N)

Else, return N.




Example

N = -2

Absolute Value:

- (-2) which is 2

N = 10

Absolute Value:

10




Program

Example

/*
 *program to find absolute value of a number
 *Language : C
 */ 
 
#include<stdio.h>

int absolute(int n)
{
    if(n < 0)            // if number is negative, say -n
    return -n;   // return -(-n) which is +n.
    
    return n;           // Otherwise, return n.
}
int main()
{
    int n;
    scanf("%d",&n);
  
    printf("Absolute of n = %d",absolute(n));
  
    return 0; 
}