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;
}