C++
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double base, exponent, result;
cout << "Enter base: ";
cin >> base;
cout << "Enter exponent: ";
cin >> exponent;
result = pow(base, exponent);
cout << base << " raised to the power " << exponent << " = " << result << endl;
return 0;
}Output
Enter base: 2 Enter exponent: 8 2 raised to the power 8 = 256
Calculate Power in C++
This program calculates the result of raising a base number to a given exponent (base^exponent). Exponentiation is a fundamental mathematical operation used extensively in programming, mathematics, physics, and computer science. The program demonstrates how to use the pow() function from the cmath library to perform this calculation efficiently.
What is Exponentiation?
Exponentiation is the mathematical operation of raising a base number to the power of an exponent.
Mathematical notation: base^exponent or base^exp
Examples:
- 2^3 = 2 × 2 × 2 = ## 8
- 5^2 = 5 × 5 = ## 25
- 10^4 = 10 × 10 × 10 × 10 = ## 10,000
- 2^8 = 2 × 2 × 2 × 2 × 2 × 2 × 2 × 2 = ## 256
Special cases:
- Any number^0 = ## 1 (by definition)
- Any number^1 = ## the number itself
- 1^any number = ## 1
Using pow() Function
result = pow(base, exponent);
Understanding pow() function:
Syntax: pow(base, exponent)
What it does:
- Calculates base raised to the power of exponent
- Returns the result as a
double
Why use pow() instead of manual calculation?
- Works with any real number (integer, decimal, negative)
- Highly optimized and efficient
- Handles edge cases automatically
- More accurate for large numbers
Summary
- Exponentiation calculates base^exponent
- Use
pow()function from<cmath>library doubledata type handles both integer and decimal exponentspow()is efficient and handles all cases (positive, negative, fractional)- Understanding exponentiation is crucial for many mathematical and programming problems
This program teaches:
- Using library functions (
pow()) - Handling different data types (
double) - Mathematical operations in programming
- Understanding function parameters and return values