Write a program to find the power of a given number using stack.
✅ Step-by-Step Explanation
🔹 1. Stack Implementation
- Array
stack[MAX]
stores elements - Integer
top
tracks the top position push()
adds elements with overflow checkpop()
removes elements with underflow check
🔹 2. Push Phase
for(i = 0; i < exp; i++) {
push(base);
}
- Pushes the base number onto stack 'exp' times
- Example: base=3, exp=4 → stack becomes [3,3,3,3]
🔹 3. Pop and Multiply Phase
for(i = 0; i < exp; i++) {
result *= pop();
}
- Pops each element and multiplies with result
- LIFO property ensures correct multiplication order
- Example: 3 × 3 × 3 × 3 = 81
🔹 4. Result Output
- Prints the final exponentiation result
- Uses
%lld
format specifier forlong long
result
🖨️ Example Runs
Example 1:
Enter base number: 2 Enter exponent: 5 2^5 = 32
Example 2:
Enter base number: 3 Enter exponent: 4 3^4 = 81
📌 Key Concepts Covered
Stack Operations
LIFO principle implemented with push/pop functions
Exponentiation
Calculating powers through repeated multiplication
Error Handling
Stack overflow/underflow detection
Data Types
Using
long long
for larger resultsAlgorithm Design
Creative use of stack for arithmetic operations
No comments:
Post a Comment