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


Enter Base: 3
Enter Exponent: 3

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
  int base, exponent;

  // public functions with two int type parameters
  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;


RUN 1:
Enter Base:10
Enter Exponent:4

RUN 2:
Enter Base: 9
Enter Exponent: 9


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) »

Comments and Discussions!

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