📖 Scenario: You are building a simple calculator that can evaluate postfix expressions (also called Reverse Polish Notation). This is useful in calculators and computer programs that process mathematical expressions without parentheses.
🎯 Goal: Build a program that uses a stack to evaluate a postfix expression containing single-digit numbers and operators +, -, *, and /.
📋 What You'll Learn
Create a stack to hold integers
Use a string variable to store the postfix expression
Loop through each character in the postfix expression
Push numbers onto the stack
Pop two numbers for each operator and apply the operation
Push the result back onto the stack
Print the final result from the stack
💡 Why This Matters
🌍 Real World
Postfix expression evaluation is used in calculators and compilers to process mathematical expressions efficiently without parentheses.
💼 Career
Understanding stacks and expression evaluation is important for software developers working on interpreters, calculators, and compilers.
Progress0 / 4 steps
1
Create the postfix expression string
Create a string variable called postfix and set it to the exact value "231*+9-".
DSA C#
Hint
The postfix expression is a string of characters representing numbers and operators. Use double quotes to create the string.
2
Create a stack to hold integers
Create a stack of integers called stack using Stack<int>.
DSA C#
Hint
Use Stack<int> and new Stack<int>() to create the stack.
3
Evaluate the postfix expression using the stack
Use a for loop with variable i to iterate over postfix. Inside the loop, get the character ch at index i. If ch is a digit, push its integer value onto stack. Otherwise, pop two integers from stack into val2 and val1, apply the operator ch to val1 and val2, and push the result back onto stack. Use switch for operators +, -, *, and /.
DSA C#
Hint
Use char.IsDigit(ch) to check if ch is a number. Convert it to int by subtracting '0'. Use stack.Pop() to get values for operations.
4
Print the final result from the stack
Print the top value of stack using Console.WriteLine(stack.Peek()).
DSA C#
Hint
The final result is the only value left on the stack. Use stack.Peek() to get it without removing it, then print it.
Practice
(1/5)
1. What is the main data structure used to evaluate a postfix expression?
easy
A. Array
B. Queue
C. Stack
D. Linked List
Solution
Step 1: Understand postfix evaluation process
Postfix expressions are evaluated by pushing operands onto a stack and popping them when an operator is encountered. The stack allows last-in, first-out access which is perfect for postfix evaluation.
2. Which of the following C# code snippets correctly pushes an integer operand onto a stack named stack?
easy
A. stack.Push(operand);
B. stack.Add(operand);
C. stack.Insert(operand);
D. stack.Enqueue(operand);
Solution
Step 1: Recall C# Stack.Push method
In C#, the method to add an element to a stack is Push. Enqueue is for queues; Add and Insert are not stack methods.
Final Answer:
stack.Push(operand); -> Option A
Quick Check:
Use Push() to add to stack [OK]
Hint: Use Push() to add items to stack in C# [OK]
Common Mistakes:
Using Enqueue which is for queues
Using Add or Insert which are not stack methods
Confusing stack with list methods
3. What is the output of the following C# code that evaluates the postfix expression "23+5*"?
string expr = "23+5*";
Stack<int> stack = new Stack<int>();
foreach (char c in expr)
{
if (char.IsDigit(c))
stack.Push(c - '0');
else
{
int b = stack.Pop();
int a = stack.Pop();
if (c == '+') stack.Push(a + b);
else if (c == '*') stack.Push(a * b);
}
}
Console.WriteLine(stack.Pop());
medium
A. 25
B. 15
C. 10
D. Error
Solution
Step 1: Trace code execution
Push 2, push 3; '+' pops b=3, a=2, push 5. Push 5; '*' pops b=5, a=5, push 25. Final pop prints 25.
Final Answer:
25 -> Option A
Quick Check:
(2+3)*5 = 25 [OK]
Hint: Calculate stepwise: operands pushed, operators pop two values [OK]
Common Mistakes:
Mixing operand order when popping
Confusing '+' and '*' operations
Forgetting to convert char digits to int
4. Identify the error in the following C# code snippet that evaluates a postfix expression:
string expr = "82/";
Stack<int> stack = new Stack<int>();
foreach (char c in expr)
{
if (char.IsDigit(c))
stack.Push(c - '0');
else
{
int a = stack.Pop();
int b = stack.Pop();
if (c == '/') stack.Push(b / a);
}
}
Console.WriteLine(stack.Pop());
medium
A. Stack is not initialized
B. Operands are popped in wrong order
C. Division operator is not handled
D. Digits are not converted to integers
Solution
Step 1: Trace popping and computation for division
Push 8, push 2 (top=2). For '/', b=Pop()=2 (right), a=Pop()=8 (left), but pushes b/a=2/8=0 instead of a/b=8/2=4. Operands popped correctly but used/applied in wrong order for non-commutative division.
Final Answer:
Operands are popped in wrong order -> Option B
Quick Check:
Pop right first (b), left second (a), compute a / b [OK]
Hint: Pop second operand first, then first operand for correct order [OK]
Common Mistakes:
Swapping operand order causing wrong division
Not handling division operator
Forgetting to convert char to int
5. Given the postfix expression "6523+8*+3+*", what is the final result after evaluation using a stack?