Sunday, 17 August 2025

Write a program to find the power of a given number using stack.

Write a program to find the power of a given number using stack.

stack_exponent.c
#include <stdio.h>
#define MAX 100

// Stack structure
int stack[MAX];
int top = -1;

// Function to push an element onto stack
void push(int val) {
    if(top == MAX - 1) {
        printf("Stack Overflow\n");
    } else {
        top++;
        stack[top] = val;
    }
}

// Function to pop an element from stack
int pop() {
    if(top == -1) {
        printf("Stack Underflow\n");
        return -1;
    } else {
        int val = stack[top];
        top--;
        return val;
    }
}

int main() {
    int base, exp, i;
    long long result = 1;

    printf("Enter base number: ");
    scanf("%d", &base);
    printf("Enter exponent: ");
    scanf("%d", &exp);

    // Step 1: Push 'base' onto stack 'exp' times
    for(i = 0; i < exp; i++) {
        push(base);
    }

    // Step 2: Pop elements and multiply
    for(i = 0; i < exp; i++) {
        result *= pop();
    }

    printf("%d^%d = %lld\n", base, exp, result);

    return 0;
}

✅ Step-by-Step Explanation

🔹 1. Stack Implementation

  • Array stack[MAX] stores elements
  • Integer top tracks the top position
  • push() adds elements with overflow check
  • pop() 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 for long 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 results
Algorithm Design
Creative use of stack for arithmetic operations

No comments:

Post a Comment

Total Pageviews

Search This Blog

Write a program which performs the following operations using a simple queue. : insert() -> delete() -> display()

Write a program which performs the following operations using a simple queue. : insert() -> delete() -> display() ...