0% found this document useful (0 votes)
8 views1 page

Power Function CPP

Uploaded by

aditiaggarwalsgi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views1 page

Power Function CPP

Uploaded by

aditiaggarwalsgi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

C++ Program to Calculate Power

This program calculates the power of a number using a function with a default argument. If the
exponent is not provided, it defaults to 2 (squares the number).

#include <iostream>
using namespace std;

// Function to calculate power


double power(double n, int p = 2) {
double result = 1;
for (int i = 1; i <= p; i++) {
result *= n;
}
return result;
}

int main() {
double n;
int p;

cout << "Enter the base number: ";


cin >> n;

cout << "Enter the power (press 0 if you want to use default 2): ";
cin >> p;

if (p == 0) {
cout << n << " raised to default power 2 is " << power(n) << endl;
} else {
cout << n << " raised to power " << p << " is " << power(n, p) << endl;
}

return 0;
}

You might also like