Learn about Absolute value in C without using the predefined function in the below code example. Also refer the comments in the code snippet to get a detailed view about what’s actually happening.
Contents
Absolute value in C without using the predefined function
The if block statement is used in this C code. If the number is negative, convert it to a positive number; else, it will remain as is. The minus operator (-) can be used to transform a negative number to a positive number. Finally, the printf function is used to display the output on the screen.
Program:
#include<stdio.h>
int main()
{
double n;
printf("Enter a number: ");
scanf("%f",&n);
if(n<0.0) n = -n ;
printf("Absolute value = %f\n", n);
return 0;
}
Output:
Enter a number: 3
Absolute value = 3
Hope above code works for you and Refer the below Related Codes to gain more insights. Happy coding and come back again.
Similar Codes :
fabs() function to find absolute value in C
labs() function to find absolute value in C