[go: up one dir, main page]

0% found this document useful (0 votes)
20 views3 pages

Week 6 - Group 17 CSE - C

Some engineering papers

Uploaded by

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

Week 6 - Group 17 CSE - C

Some engineering papers

Uploaded by

hitikhatod
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

Write a C program for conversion of an infix expression to postfix, using stack?

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <ctype.h>

#define MAX_SIZE 100

// Stack structure

typedef struct {

char array[MAX_SIZE];

int top;

} Stack;

// Function to initialize stack

void initializeStack(Stack *s) {

s->top = -1;

// Function to check if stack is empty

int isEmpty(Stack *s) {

return s->top == -1;

// Function to check if stack is full

int isFull(Stack *s) {

return s->top == MAX_SIZE - 1;

// Function to push element onto stack

void push(Stack *s, char c) {

if (!isFull(s))

s->array[++(s->top)] = c;

else

printf("Stack overflow\n");

// Function to pop element from stack

char pop(Stack *s) {

if (!isEmpty(s))

return s->array[(s->top)--];

else {
printf("Stack underflow\n");

return '\0';

// Function to return top element of stack

char peek(Stack *s) {

if (!isEmpty(s))

return s->array[s->top];

else {

printf("Stack is empty\n");

return '\0';

// Function to determine precedence of operators

int precedence(char op) {

switch (op) {

case '+':

case '-':

return 1;

case '*':

case '/':

return 2;

default:

return 0;

// Function to convert infix expression to postfix

void infixToPostfix(char *infix, char *postfix) {

Stack stack;

initializeStack(&stack);

int j = 0;

for (int i = 0; infix[i]; ++i) {

char c = infix[i];

if (isalnum(c))

postfix[j++] = c;

else if (c == '(')
push(&stack, c);

else if (c == ')') {

while (!isEmpty(&stack) && peek(&stack) != '(')

postfix[j++] = pop(&stack);

pop(&stack); // Discard '('

} else {

while (!isEmpty(&stack) && precedence(c) <= precedence(peek(&stack)))

postfix[j++] = pop(&stack);

push(&stack, c);

while (!isEmpty(&stack))

postfix[j++] = pop(&stack);

postfix[j] = '\0';

int main() {

char infix[MAX_SIZE];

char postfix[MAX_SIZE];

printf("Enter infix expression: ");

fgets(infix, MAX_SIZE, stdin);

infixToPostfix(infix, postfix);

printf("Postfix expression: %s\n", postfix);

return 0;

You might also like