abs() returns the absolute value of an int. It is declared in <stdlib.h>. The result is non-negative for representable inputs.
int abs(int value);
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int value = -25;
printf("%d\n", abs(value));
return 0;
}
Output
25
#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().
#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;
}
#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;
}
#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;
}
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.