abs() in C: Absolute Value

abs() returns the absolute value of an int. It is declared in <stdlib.h>. The result is non-negative for representable inputs.

Syntax Top ↑

int abs(int value);

Basic Example Top ↑

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

int main(void) {
    int value = -25;

    printf("%d\n", abs(value));
    return 0;
}

Output

25

Absolute Difference Top ↑

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

int main(void) {
    int a = 42;
    int b = 57;

    printf("Difference: %d\n", abs(a - b));
    return 0;
}

For floating-point values use fabs() from <math.h>, not abs().

Preserved Type-Specific abs() Examples Top ↑

Floating-Point Absolute Value with fabs()

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

int main(void) {
    double first = 12.35;
    double second = -35.45;

    printf("%.2f\n", fabs(first));
    printf("%.2f\n", fabs(second));

    return 0;
}

Long Integer Absolute Value with labs()

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

int main(void) {
    long first = 123456L;
    long second = -3456789L;

    printf("%ld\n", labs(first));
    printf("%ld\n", labs(second));

    return 0;
}

abs() with User Input

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

int main(void) {
    int value;

    printf("Enter an integer: ");
    if (scanf("%d", &value) != 1) {
        printf("Invalid input.\n");
        return 1;
    }

    printf("Absolute value: %d\n", abs(value));
    return 0;
}




plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer