Write a program to calculate factorial of given number using stack

विवरण (Problem Statement)

दिए गए किसी भी धनात्मक संख्या (n) का Factorial निकालना है।
Factorial का सूत्र:

इस प्रोग्राम में हम Stack (LIFO – Last In First Out) का उपयोग करेंगे।

तर्क (Logic using Stack)

  1. सबसे पहले संख्या n को Stack में push किया जाता है

  2. फिर stack से एक-एक करके तत्व pop करते हैं

  3. हर pop किए गए मान को result में multiply करते हैं

  4. अंत में result ही factorial होगा

C++ Program: Factorial using Stack

#include <iostream>
using namespace std;

#define MAX 20

int stack[MAX];
int top = -1;

// Push function
void push(int x)
{
if (top == MAX – 1)
cout << “Stack Overflow\n”;
else
stack[++top] = x;
}

// Pop function
int pop()
{
if (top == -1)
return 1;
else
return stack[top–];
}

int main()
{
int n;
long long fact = 1;

cout << “कोई संख्या दर्ज करें: “;
cin >> n;

// Stack में 1 से n तक की values push करना
for (int i = 1; i <= n; i++)
{
push(i);
}

// Stack से pop करके factorial निकालना
while (top != -1)
{
fact = fact * pop();
}

cout << “Factorial = ” << fact;

return 0;
}

उदाहरण (Example)

Input: 5

Process (Stack में):

Push → 1 2 3 4 5

Pop → 5 × 4 × 3 × 2 × 1

Output:

Factorial = 120

Speak Your Mind

*

error: Content is protected !!