Home » Programming Tips & Tricks » C++ - Tips & Tricks

Create your own abs() Macro/Function to get Absolute value in C++

By: IncludeHelp, on 16 FEB 2017

Learn: How to get absolute value of any integer without using abs() function of stdlib.h in C, C++ programming language? Here, we will learn to create our own ABS() Macro/Function.

First of all, we should learn about abs() function

What is abs()?

This is a library function which is declared in stdlib.h, it returns absolute value of any integer. The real/actual magnitude of a number (numerical value) without sign is known as Absolute value.

For example - if there is a value -10 its absolute value will be 10, and if the value is 10 its absolute value will also be 10.

Find absolute value using abs() - A stdlib.h library function

Consider the example, here we will find the absolute value by using abs() function.

#include <iostream>
#include <stdlib.h>

using namespace std;

int main()
{
   int val;
   
   val=-10;
   cout<<"Absolute value of "<<val<<" is "<<abs(val)<<endl;
   val=10;
   cout<<"Absolute value of "<<val<<" is "<<abs(val)<<endl;
   
   return 0;
}

Output

Absolute value of -10 is 10 
Absolute value of 10 is 10 

Find absolute value without using abs() - by using our own ABS() function

Here, we will not use library function abs(), we are using two methods to get the absolute value of any integer number.

  1. Using Parameterized Macro
  2. Using User Define Function

1) Parameterized Macro

Here is the statement of Parameterized Macro

#define ABS(N) ((N<0)?(-N):(N))

Example:

#include <iostream>

using namespace std;

#define ABS(N) ((N<0)?(-N):(N))

int main()
{
   int val;
   
   val=-10;
   cout<<"Absolute value of "<<val<<" is "<<ABS(val)<<endl;
   val=10;
   cout<<"Absolute value of "<<val<<" is "<<ABS(val)<<endl;
   
   return 0;
}

Output

Absolute value of -10 is 10 
Absolute value of 10 is 10 

2) User Define Function

Here is the function body of the ABS() - A user define function, that will take an integer number and return absolute value.

Example: function code

int ABS(int N)
{
    return ((N<0)?(-N):(N));
}

This is not only a C++ programming trick to get absolute values, we can also use it in C programming too.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.