Home » abs() function in C

abs() function in C

by Online Tutorials Library

abs() function in C

In this topic, we will discuss the abs function in the C programming language. The abs () function is a predefined function in the stdlib.h header file to return the absolute value of the given integers. So, if we want to return the absolute value of a given number, we need to implement the stdlib.h header file in the C program. The abs() function only returns the positive numbers. For example: Suppose we have an integer number -5, and we want to get the absolute number, we use the abs() function to return the positive number as 5. Furthermore, if we pass any positive number, it returns the same number.

abs() function in C

Syntax

In the above syntax, x is an integer data type that holds either negative or positive numbers and passed in the abs() function to return the positive value because the function has an integer data type.

Note: The abs() function always returns a positive number even if the given number is either negative or positive.

Program to get the absolute value of a number using the abs() function

Let’s consider an example to print the absolute number using the abs() function in C program.

Prog.c

Output

Enter a number to display the absolute value: -35     The absolute value of -35 is 35.  

Program to print the absolute values of the given integers using abs() function

Let’s create a program to print the absolute values of the given numbers using abs() function in C.

Absolute.c

Output

The absolute value of 27 is 27   The absolute value of -16 is 16   The absolute value of -125 is 125   The absolute value of 18 is 18   The absolute value of -29 is 29   The absolute value of 0 is 0  

Program to print the absolute values between two integers using for loop

Let’s consider an example to print the absolute value between two integers using for loop in C program.

Abs2.c

Output

Enter the first negative number:   -5   Enter the last number from which you want to get the absolute number:   5     The absolute value of -5 is 5.   The absolute value of -4 is 4.   The absolute value of -3 is 3.   The absolute value of -2 is 2.   The absolute value of -1 is 1.   The absolute value of 0 is 0.   The absolute value of 1 is 1.   The absolute value of 2 is 2.   The absolute value of 3 is 3.   The absolute value of 4 is 4.   The absolute value of 5 is 5.  

Program to get the absolute value without using the abs() function

Let’s create a C program to get the absolute value of a number without using the abs() function.

Abs.c

Output

Enter a number to display the absolute value: -8   The absolute value is: 8  

As we can see in the above program, we have passed an integer number from the user. If the given number is negative, it will be multiplied by (-1) to return the positive number. And if the number is positive, it returns the same number.


You may also like