Absolute value of a number

C program to find absolute value of a number.

If number is positive, then its absolute value is the number itself.
If number is negative, then absolute value is negation of that number.
i.e.
if x > 0, then |x| = x
if x < o, then |x| = -x

The above problem can be solved in two ways:
Without using abs() function, using if else as explained in method 1 tab.
Using abs() library function as explained in method 2 tab.

Program

#include<stdio.h>
#include<conio.h>
void main()
{
    int number;

    printf("Enter the number\t:");
    scanf("%d",&number);

    if(number < 0)
		printf("\nAbsolute value of the number entered is \t: %d",(-1) * number);
    else
		printf("\nAbsolute value of the number entered is \t: %d",number);

    getch();
}

Output

********** Run1 **********
Enter the number        :5

Absolute value of the number entered is         : 5


********** Run2 **********

Enter the number        :-2

Absolute value of the number entered is         : 2

Explanation

Accept a number whose absolute value you want to find using the scanf() function. Then, using the if-else construct check if the number is positive or negative.
If the number is positive, then the absolute value remains the same.
If the number is less than 0 then multiply the number by -1 to make it positive.

Program

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
    int number;

    printf("Enter the number\t:");
    scanf("%d",&number);

    printf("\nAbsolute value of the number entered is \t: %d",abs(number));

    getch();
}

Output

********** Run1 **********
Enter the number        :-5

Absolute value of the number entered is         : 5


********** Run2 **********
Enter the number        :7

Absolute value of the number entered is         : 7

Explanation

abs() function in C returns the absolute value of an integer. The absolute value of a number is always positive.
Syntax for abs() function in C is as follows:
int abs (int n);
stdlib.h header file supports abs() function in C language.