Power of a Number using C++ Function Overloading

Function Overloading Output

This article explains the different types of function overloading methods to compute the power of a number (xn) using C++. In this tutorial, I have used Dev C++ v5.11 software for compiling the C++ program.

Overloading in C++

In C++ language, overloading is a method used to define more than one functions (function overloading) or operators (operator overloading) with the same name and different data types or parameters.

Example for function overloading, add (int a, int b)
add (int a, int b, int c)
add (float a, float b)
add (float a, int b)

Example for operator overloading, Increment i(5); // Class declaration and input value
i++; // Calling of a function "void operator++()" which assigns x += 5;
i.Print(); // Output is 10

Source Code

// Computing m^n using function overloading.
#include <iostream>
#include <conio.h>
using namespace std;

long double power (double m, int n) {
  long double x = 1;
  for (int i = 0; i < n; i++) {
    x *= m;
  }
  return x;
}

long power (int m, int n) {
  long x = 1;
  for (int i = 0; i < n; i++) {
    x *= m;
  }
  return x;
}

int main() {
  system("cls");
  double a;
  int b, c, d;
  cout << "Computing m\xFC for large numbers:-\n";
  cout << "\nEnter m and n values: ";
  cin >> a >> b;
  cout << "Result of " << a << "^" << b << " is " << power(a, b);
  cout << "\n\nComputing m\xFC for small numbers:-\n";
  cout << "\nEnter m and n values: ";
  cin >> c >> d;
  cout << "Result of " << c << "^" << d << " is " << power(c, d);
  getch();
}

Comments

Most Popular Posts

TNEB Bill Calculator

TNEB Bill Calculator (New)

Technical Questions