Home »
C++ Programs
C++ program to find the power of a number using class
Given a number, we have to find its power using class and object approach.
Submitted by Shubh Pachori, on August 05, 2022
Problem statement
Given a number, we have to find its power using class and object approach.
Example:
Input:
Enter Base: 3
Enter Exponent: 3
Output:
3^3 = 27
C++ code to find the power of a number using class and object approach
#include <iostream>
using namespace std;
// create a class
class Power {
// private data members
private:
int base, exponent;
// public functions with two int type parameters
public:
int power(int b, int e) {
// copying the values of the parameters in the data members
base = b;
exponent = e;
// decalring two int type variable for indexing and storing result
int index, result = 1;
// for loop for calculate the result of base^exponent
for (index = 0; index < exponent; index++) {
result *= base;
}
// returning the result
return result;
}
};
int main() {
// create a object
Power P;
// declaring int type variables for opeartions
int b, e, result;
cout << "Enter Base:";
cin >> b;
cout << "Enter Exponent:";
cin >> e;
// calling the function using object
result = P.power(b, e);
cout << b << "^" << e << "=" << result;
return 0;
}
Output
RUN 1:
Enter Base:10
Enter Exponent:4
10^4=10000
RUN 2:
Enter Base: 9
Enter Exponent: 9
9^9=387420489
Explanation
In the above code, we have created a class Power, two int type data members base and exponent to store the base and its exponent, and a public member function power() to calculate the power of the given integer number.
In the main() function, we are creating an object P of class Power, reading an integer number by the user, and finally calling the power() member function to calculate the power of the given integer number. The power() function contains the logic to calculate the power of the given number and printing the result.
C++ Class and Object Programs (Set 2) »