C Program to Find the Absolute Value of a Number

Write a C program to find the absolute value of a number, a positive integer of a given number. In C programming, the stdlib header has an abs function that prints the absolute value.

#include <stdio.h>
#include <stdlib.h>

int main()
{   
    int num;
    
    printf("Enter Number to find Absolute Value = ");
    scanf("%d",&num);

    int abNum = abs(num);

    printf("\nActual Number   = %d", num); 
    printf("\nAbsolute Number = %d\n", abNum);
}
C Program to Find the Absolute Value of a Number

In C language math header file has a fabs function that accepts the double and floating point numbers and finds the absolute value. In this c program, we use fabs to find the absolute value of floating-point numbers.

#include <stdio.h>
#include <math.h>

int main()
{   
    double num;
    float num2;
    
    printf("Enter Double Number = ");
    scanf("%lf",&num);

    printf("Enter Float Number  = ");
    scanf("%f",&num2);

    double abNum = fabs(num);

    printf("\nActual Double Number   = %lf", num); 
    printf("\nAbsolute Double Number = %lf\n", abNum);

    float abNum2 = fabs(num2);

    printf("\nActual Float Number   = %.3f", num2); 
    printf("\nAbsolute Float Number = %.3f\n", abNum2);
}
Enter Double Number = -34556.8765
Enter Float Number  = -2345.239f    

Actual Double Number   = -34556.876500
Absolute Double Number = 34556.876500

Actual Float Number   = -2345.239
Absolute Float Number = 2345.239

This c example uses the labs function to find the absolute value of a long number.

#include <stdio.h>
#include <stdlib.h>

int main()
{   
    long num;
    
    printf("Enter Number = ");
    scanf("%ld",&num);

    long abNum = labs(num);

    printf("\nActual   = %ld", num); 
    printf("\nAbsolute Number = %ld\n", abNum);
}
Enter Number = -654323456

Actual   = -654323456
Absolute Number = 654323456

It is a simple code to find the absolute value of any number in c using an if statement that checks whether the number less than zero. If true, assign a positive number.

#include <stdio.h>

int main()
{   
    int num;
    
    printf("Enter Number = ");
    scanf("%d",&num);

    if(num < 0)
    {
        num = -num;
    }
    printf("\nAbsolute Number = %d\n", num);
}
Enter Number = -99

Absolute Number = 99

About Suresh

Suresh is the founder of TutorialGateway and a freelance software developer. He specialized in Designing and Developing Windows and Web applications. The experience he gained in Programming and BI integration, and reporting tools translates into this blog. You can find him on Facebook or Twitter.