#include <stdio.h>
#include <math.h>
int main(void){
int x,y;
x=12;
y=-35;
x = abs(x);
y = abs(y);
printf("%d \n", x);
printf("%d", y);
return 0;
}
The above code will give this output.
12
35
Example with float variables by using fabs()
#include <stdio.h>
#include <math.h>
int main(void){
float x,y;
x=12.35;
y=-35.45;
x = fabs(x);
y = fabs(y);
printf("%f \n", x);
printf("%f", y);
return 0;
}
Output is here
12.350000
35.450001
Example with long variables by using labs()
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main(void){
long int x,y;
x=12.35;
y=-35.45;
x = labs(x);
y = labs(y);
printf("%ld \n", x);
printf("%ld", y);
return 0;
}
12.35
35.45
Example: Using abs() with User Input
#include <stdio.h>
#include <math.h>
int main(void){
int x;
printf("Enter an integer: ");
scanf("%d", &x);
printf("The absolute value of %d is %d\n", x, abs(x));
return 0;
}
Output:
Enter an integer: -25
The absolute value of -25 is 25
Example: Handling Multiple Data Types
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main(void){
int x = -15;
float y = -23.45;
long z = -3456789;
printf("abs(%d) = %d\n", x, abs(x));
printf("fabs(%.2f) = %.2f\n", y, fabs(y));
printf("labs(%ld) = %ld\n", z, labs(z));
return 0;
}