0% found this document useful (0 votes)
4 views5 pages

C++ Calculator: Infix to Postfix Evaluation

The provided code implements a simple calculator that takes a mathematical expression as input, converts it to postfix notation, and evaluates the result. It includes a stack data structure for managing operators and operands, and functions for parsing expressions, converting to postfix, and evaluating the postfix expression. The main program prompts the user for input, processes the expression, and displays the evaluation result.

Uploaded by

migueljethrocruz
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views5 pages

C++ Calculator: Infix to Postfix Evaluation

The provided code implements a simple calculator that takes a mathematical expression as input, converts it to postfix notation, and evaluates the result. It includes a stack data structure for managing operators and operands, and functions for parsing expressions, converting to postfix, and evaluating the postfix expression. The main program prompts the user for input, processes the expression, and displays the evaluation result.

Uploaded by

migueljethrocruz
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Source code:

[Link]

#include "calculator.h"

int main() {
char expression[100]; // Array to store the input expression
char postfix[100]; // Array to store the postfix expression

// Prompt user for input


std::cout << "Enter a mathematical expression: ";
std::cin >> expression; // Read the input expression

// Parse the expression


parseExpression(expression); // Call function to parse and display tokens

// Convert to postfix
convertToPostfix(expression, postfix); // Call function to convert to postfix

// Evaluate the postfix expression


float result = evaluatePostfix(postfix); // Call function to evaluate postfix

std::cout << "Evaluation Result: " << result << std::endl; // Display the result

return 0; // End of the program


}

CALCULATOR.H

#ifndef CALCULATOR_H
#define CALCULATOR_H

#include <iostream>
#include <cstring> // For cstring functions
#include <cctype> // For isdigit()

// Node structure for the linked list


struct Node {
float data; // Data stored in the node (changed to float for multi-digit support)
Node* next; // Pointer to the next node in the list
};
// Stack class using linked list
class Stack {
public:
Stack(); // Constructor to initialize the stack
~Stack(); // Destructor to clean up the stack
void push(float value); // Function to add an element to the stack
float pop(); // Function to remove an element from the stack
float peek(); // Function to see the top element of the stack
bool isEmpty(); // Function to check if the stack is empty

private:
Node* top; // Pointer to the top of the stack
};

// Function declarations
void parseExpression(const char* expression); // Function to parse the input expression
void convertToPostfix(const char* expression, char* postfix); // Function to convert infix to postfix
float evaluatePostfix(const char* postfix); // Function to evaluate the postfix expression
int precedence(char op); // Function to determine operator precedence

#endif // CALCULATOR_H

[Link]

#include "calculator.h" // Include the header file for declarations and dependencies

// Stack class constructor


Stack::Stack() : top(nullptr) {} // Initialize the top pointer to nullptr, creating an empty stack

// Stack class destructor


Stack::~Stack() {
while (!isEmpty()) { // Loop while the stack is not empty
pop(); // Remove each element to clean up memory
}
}

// Push function to add an element to the stack


void Stack::push(float value) {
Node* newNode = new Node; // Create a new node dynamically
newNode->data = value; // Set the node's data to the given value
newNode->next = top; // Point the new node to the current top node
top = newNode; // Update the top pointer to the new node
}

// Pop function to remove an element from the stack


float Stack::pop() {
if (isEmpty()) { // Check if the stack is empty before popping
std::cerr << "Stack underflow" << std::endl; // Print an error message if empty
return 0; // Return a default value (0) when underflow occurs
}
Node* temp = top; // Store the top node temporarily
float value = top->data; // Retrieve the value of the top node
top = top->next; // Move the top pointer to the next node
delete temp; // Delete the old top node to free memory
return value; // Return the popped value
}

// Peek function to see the top element of the stack


float Stack::peek() {
if (isEmpty()) { // Check if the stack is empty
return 0; // Return a default value (0) if the stack is empty
}
return top->data; // Return the data of the top node
}

// Check if the stack is empty


bool Stack::isEmpty() {
return top == nullptr; // Return true if the stack is empty (top is nullptr)
}

// Function to parse the input expression


void parseExpression(const char* expression) {
std::cout << "Parsed Tokens: "; // Print a header for the parsed tokens
for (int i = 0; expression[i] != '\0'; ++i) { // Loop through each character of the input expression
std::cout << expression[i] << " "; // Print each character as a token
}
std::cout << std::endl; // Print a newline after the tokens
}

// Function to convert infix expression to postfix


void convertToPostfix(const char* expression, char* postfix) {
Stack stack; // Create a stack to store operators
int j = 0; // Initialize index for the postfix expression
for (int i = 0; expression[i] != '\0'; ++i) { // Loop through each character in the infix expression
char token = expression[i]; // Get the current character as a token
if (isdigit(token)) { // Check if the token is a digit
while (isdigit(expression[i])) { // Accumulate multi-digit numbers
postfix[j++] = expression[i++]; // Append each digit to the postfix expression
}
postfix[j++] = ' '; // Add a space to separate numbers in the postfix expression
i--; // Decrement i to avoid skipping the next character
} else if (token == '(') { // If the token is an opening parenthesis
[Link](token); // Push it onto the stack
} else if (token == ')') { // If the token is a closing parenthesis
while (![Link]() && [Link]() != '(') { // Pop until an opening parenthesis is found
postfix[j++] = [Link](); // Append operators to the postfix expression
}
[Link](); // Remove the opening parenthesis from the stack
} else { // If the token is an operator
while (![Link]() && precedence([Link]()) >= precedence(token)) { // Compare
precedence
postfix[j++] = [Link](); // Pop and append higher precedence operators
}
[Link](token); // Push the current operator onto the stack
}
}
while (![Link]()) { // Pop any remaining operators from the stack
postfix[j++] = [Link](); // Append them to the postfix expression
}
postfix[j] = '\0'; // Null-terminate the postfix expression
std::cout << "Postfix Expression: " << postfix << std::endl; // Print the generated postfix expression
}

// Function to evaluate the postfix expression


float evaluatePostfix(const char* postfix) {
Stack stack; // Create a stack to store operands
int i = 0; // Initialize index for traversing the postfix expression

while (postfix[i] != '\0') { // Loop through the postfix expression


char token = postfix[i]; // Get the current token
if (isdigit(token)) { // If the token is a digit
float number = 0; // Initialize a variable to accumulate the number
while (isdigit(postfix[i])) { // Accumulate multi-digit numbers
number = number * 10 + (postfix[i] - '0'); // Convert character to integer and accumulate
i++;
}
[Link](number); // Push the complete number onto the stack
} else if (token != ' ') { // If the token is not a space (operator case)
float operand2 = [Link](); // Pop the top element as the second operand
float operand1 = [Link](); // Pop the next element as the first operand
switch (token) { // Perform the operation based on the operator
case '+': [Link](operand1 + operand2); break; // Addition
case '-': [Link](operand1 - operand2); break; // Subtraction
case '*': [Link](operand1 * operand2); break; // Multiplication
case '/': [Link](operand1 / operand2); break; // Division
}
}
i++; // Move to the next token
}
return [Link](); // Pop and return the final result from the stack
}

// Helper function to determine precedence of operators


int precedence(char op) {
switch (op) {
case '+':
case '-': return 1; // Low precedence for addition and subtraction
case '*':
case '/': return 2; // Higher precedence for multiplication and division
default: return 0; // No precedence for other characters
}
}

You might also like