Test 1 sol
Test 1 sol
Key Solution
int factorial(int n) {
if (n == 0) return 1; // Base case
return n * factorial(n - 1); // Recursive call
}
A stack can be implemented using an array by maintaining a variable top to track the topmost
element in the stack.
Operations:
Example (C++)
#include <iostream>
using namespace std;
class Stack {
private:
int arr[MAX];
int top;
public:
Stack() { top = -1; } // Constructor initializes stack as empty
int main() {
Stack stack;
stack.push(10);
stack.push(20);
stack.push(30);
return 0;
}
Output:
Top element: 30
Popped element: 30
Top element after pop: 20
Easy to implement.
Fast access due to contiguous memory.
Limitations: