SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,julia Lobur
Chapter:
Procedural Abstraction And Functions That Return A Value
Exercise:
Programming Projects
Question:11 | ISBN:9780321531346 | Edition: 7

Question

That we are “blessed” with several absolute value functions is an accident of history. C libraries were already available when C++ arrived; they could be easily used, so they were not rewritten using function overloading. You are to find all the absolute value functions you can, and rewrite all of them overloading the abs function name. At a minimum you should have the int , long , float , and double types represented.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

PROGRAM CODE:

// abs_overload.h

#ifndef ABS_OVERLOAD_H
#define ABS_OVERLOAD_H

// Function overloading for int
int abs(int num) {
    return (num < 0) ? -num : num;
}

// Function overloading for long
long abs(long num) {
    return (num < 0) ? -num : num;
}

// Function overloading for float
float abs(float num) {
    return (num < 0.0) ? -num : num;
}

// Function overloading for double
double abs(double num) {
    return (num < 0.0) ? -num : num;
}

#endif
//Header section
#include <iostream>
#include "abs_overload.h"
using namespace std;
//main program
int main() 
{
    //Initilize variables
    int num1 = -5;
    long num2 = -1234567890L;
    float num3 = -3.14f;
    double num4 = -2.71828;
     //Display the output using abs function
    cout << "Absolute value of " << num1 << ": " << abs(num1) << endl;
    cout << "Absolute value of " << num2 << ": " << abs(num2) << endl;
    cout << "Absolute value of " << num3 << ": " << abs(num3) << endl;
    cout << "Absolute value of " << num4 << ": " << abs(num4) << endl;

    return 0;
}

OUTPUT OF THE PROGRAM CODE:

Absolute value of -5: 5
Absolute value of -1234567890: 1234567890
Absolute value of -3.14: 3.14
Absolute value of -2.71828: 2.71828

 

0 0

Discussions

Post the discussion to improve the above solution.