C Program to Find the Absolute Value of a Number
In this post, we’ll learn how to find the absolute value of a given number using a simple C program. The absolute value of a number is its distance from zero, regardless of sign.
C Program Code
#include <stdio.h>
#include <stdlib.h> // For the abs() function for integers and fabs() for floating point
int main() {
double number, absolute_value;
// Prompt the user to enter a number
printf("Enter a number: ");
scanf("%lf", &number);
// Find the absolute value
absolute_value = fabs(number);
// Display the absolute value
printf("The absolute value of %.2lf is %.2lf\n", number, absolute_value);
return 0;
}
How the Program Works
- We include the standard I/O library
<stdio.h>
and<stdlib.h>
for thefabs()
function. - We declare two
double
variables:number
andabsolute_value
. - We prompt the user to enter a number and read the input using
scanf()
. - We calculate the absolute value using the
fabs()
function. - We display the result with two decimal precision using
printf()
.
Example Output
Here’s an example of what the output might look like:
Enter a number: -8.5
The absolute value of -8.50 is 8.50
Conclusion
This simple C program demonstrates how to find the absolute value of a number using the fabs()
function.
You can easily adapt it for integers by using the abs()
function instead.
C Program to Find Absolute Value Without Built-in Functions
This program calculates the absolute value of a number manually, without using any built-in functions like fabs()
or abs()
.
The absolute value is simply the number itself if it's positive or zero, and its negation if it's negative.
C Program Code
#include <stdio.h>
int main() {
double number, absolute_value;
// Prompt the user to enter a number
printf("Enter a number: ");
scanf("%lf", &number);
// Calculate absolute value manually
if (number < 0) {
absolute_value = -number;
} else {
absolute_value = number;
}
// Display the absolute value
printf("The absolute value of %.2lf is %.2lf\n", number, absolute_value);
return 0;
}
How the Program Works
- We prompt the user to enter a number.
- If the number is negative, we multiply it by -1 to make it positive.
- If the number is zero or positive, we leave it as is.
- Finally, we display the absolute value.
Example Output
Here’s what the output looks like:
Enter a number: -12.34
The absolute value of -12.34 is 12.34
Conclusion
This example demonstrates how to compute the absolute value manually without relying on built-in functions, which can be useful for learning or in environments where standard libraries are limited.