Write a C++ program that calculates the power of a given base number raised to a given exponent, where both the base and the exponent are entered by the user.
Input and Output Examples
- Input: Base = 2, Exponent = 3
Output: 2 raised to the power of 3 is 8. - Input: Base = 5, Exponent = 2
Output: 5 raised to the power of 2 is 25.
Algorithm to calculate the power of a number:
- Start the Program: Include necessary headers and declare the use of the standard namespace.
- Prompt for Input: Ask the user to enter the base and the exponent.
- Read the Input: Store the base and exponent values in variables.
- Calculate the Power: Use a method to calculate the power of the base raised to the exponent.
- Display the Output: Print the result of the power calculation.
- End the Program: Finish execution cleanly.
Below is the C++ Program with Different Methods to Calculate Power of a number:
Method 1: Using a Loop
This method calculates the power using a loop to repeatedly multiply the base by itself.
#include <iostream>
using namespace std;
int main() {
int base, exponent, result = 1; // Declare variables for the base, exponent, and result.
cout << "Enter the base: "; // Prompt the user for the base.
cin >> base; // Read the base value.
cout << "Enter the exponent: "; // Prompt the user for the exponent.
cin >> exponent; // Read the exponent value.
// Calculate the power using a loop
for (int i = 0; i < exponent; ++i) {
result *= base; // Multiply result by base for each iteration.
}
cout << base << " raised to the power of " << exponent << " is " << result << "." << endl; // Display the result.
return 0; // End the program successfully.
}
Method 2: Using the pow() Function
This method uses the pow() function from the <cmath> library to calculate the power.
#include <iostream>
#include <cmath> // Include the library for mathematical functions.
using namespace std;
int main() {
int base, exponent; // Declare variables for the base and exponent.
cout << "Enter the base: ";
cin >> base;
cout << "Enter the exponent: ";
cin >> exponent;
double result = pow(base, exponent); // Calculate the power using the pow() function.
cout << base << " raised to the power of " << exponent << " is " << result << "." << endl;
return 0;
}