Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

CDSS Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 28

CDSS NOTES:

Example program for the lex and yacc programs

This section contains example programs for the lex and yacc commands.

Together, these example programs create a simple, desk-calculator program that performs addition,
subtraction, multiplication, and division operations. This calculator program also allows you to assign
values to variables (each designated by a single, lowercase letter) and then use the variables in
calculations. The files that contain the example lex and yacc programs are as follows:

File Content
calc.lex Specifies the lex command specification file that defines the lexical analysis rules.
Specifies the yacc command grammar file that defines the parsing rules, and calls
calc.yacc
the yylex subroutine created by the lex command to provide input.

The following descriptions assume that the calc.lex and calc.yacc example programs are located in
your current directory.

Compiling the example program

To create the desk calculator example program, do the following:

1. Process the yacc grammar file using the -d optional flag (which informs the yacc command to
create a file that defines the tokens used in addition to the C language source code):

yacc -d calc.yacc

2. Use the ls command to verify that the following files were created:

y.tab.c
The C language source file that the yacc command created for the parser
y.tab.h
A header file containing define statements for the tokens used by the parser

3. Process the lex specification file:

lex calc.lex

4. Use the ls command to verify that the following file was created:

lex.yy.c
The C language source file that the lex command created for the lexical analyzer

“”

5. Compile and link the two C language source files:

cc y.tab.c lex.yy.c
6. Use the ls command to verify that the following files were created:

y.tab.o
The object file for the y.tab.c source file
lex.yy.o
The object file for the lex.yy.c source file
a.out
The executable program file
To run the program directly from the a.out file, type:
$ a.out

OR

To move the program to a file with a more descriptive name, as in the following example, and run it,
type:
$ mv a.out calculate
$ calculate
In either case, after you start the program, the cursor moves to the line below the $ (command
prompt). Then, enter numbers and operators as you would on a calculator. When you press the
Enter key, the program displays the result of the operation. After you assign a value to a variable, as
follows, the cursor moves to the next line.
m=4 <enter>
_
When you use the variable in subsequent calculations, it will have the assigned value:
m+5 <enter>
9
_

Parser source code

The following example shows the contents of the calc.yacc file. This file has entries in all three
sections of a yacc grammar file: declarations, rules, and programs.

%{
#include<stdio.h>

int regs[26];
int base;

%}

%start list

%union { int a; }

%token DIGIT LETTER

%left '|'
%left '&'
%left '+' '-'
%left '*' '/' '%'
%left UMINUS /*supplies precedence for unary minus */

%% /* beginning of rules section */

list: /*empty */
|
list stat '\n'
|
list error '\n'
{
yyerrok;
}
;
stat: expr
{
printf("%d\n",$1);
}
|
LETTER '=' expr
{
regs[$1.a] = $3.a;
}

expr: '(' expr ')'


{
$$ = $2;
}
|
expr '*' expr
{

$$.a = $1.a * $3.a;


}
|
expr '/' expr
{
$$.a = $1.a / $3.a;
}
|
expr '%' expr
{
$$.a = $1.a % $3.a;
}
|
expr '+' expr
{
$$.a = $1.a + $3.a;
}
|
expr '-' expr
{
$$.a = $1.a - $3.a;
}
|
expr '&' expr
{
$$.a = $1.a & $3.a;
}
|
expr '|' expr
{
$$.a = $1.a | $3.a;
}
|

'-' expr %prec UMINUS


{
$$.a = -$2.a;
}
|
LETTER
{
$$.a = regs[$1.a];
}

|
number
;

number: DIGIT
{
$$ = $1;
base = ($1.a==0) ? 8 : 10;
} |
number DIGIT
{
$$.a = base * $1.a + $2.a;
}
;

%%
main()
{
return(yyparse());
}

yyerror(s)
char *s;
{
fprintf(stderr, "%s\n",s);
}

yywrap()
{
return(1);
}
The file contains the following sections:

• Declarations section. This section contains entries that:


o Include standard I/O header file
o Define global variables
o Define the list rule as the place to start processing
o Define the tokens used by the parser
o Define the operators and their precedence
• Rules section. The rules section defines the rules that parse the input stream.
o %start - Specifies that the whole input should match stat.
o %union - By default, the values returned by actions and the lexical analyzer are
integers. yacc can also support values of other types, including structures. In
addition, yacc keeps track of the types, and inserts appropriate union member names so
that the resulting parser will be strictly type checked. The yacc value stack is declared
to be a union of the various types of values desired. The user declares the union, and
associates union member names to each token and nonterminal symbol having a value.
When the value is referenced through a $$ or $n construction, yacc will automatically
insert the appropriate union name, so that no unwanted conversions will take place.
o %type - Makes use of the members of the %union declaration and gives an individual
type for the values associated with each part of the grammar.
o %toksn - Lists the tokens which come from lex tool with their type.
• Programs section. The programs section contains the following subroutines. Because these
subroutines are included in this file, you do not need to use the yacc library when processing
this file.

SubroutineDescription
Main The required main program that calls the yyparse subroutine to start the program.
yyerror(s) This error-handling subroutine only prints a syntax error message.
yywrap The wrap-up subroutine that returns a value of 1 when the end of input occurs.

Lexical analyzer source code

This file contains include statements for standard input and output, as well as for the y.tab.h file. If
you use the -d flag with the yacc command, the yacc program generates that file from
the yacc grammar file information. The y.tab.h file contains definitions for the tokens that the
parser program uses. In addition, the calc.lex file contains the rules to generate these tokens from
the input stream. The following are the contents of the calc.lex file.
%{

#include <stdio.h>
#include "y.tab.h"
int c;
%}
%%
" " ;
[a-z] {
c = yytext[0];
yylval.a = c - 'a';
return(LETTER);
}
[0-9] {
c = yytext[0];
yylval.a = c - '0';
return(DIGIT);
}
[^a-z0-9\b] {
c = yytext[0];
return(c);
}
%%

/*

Program: C Program to perform arithmetic operations using switch statement

*/

#include<stdio.h>
int main() {

int x, y;

// If user provides wrong operator, we are using goto statement

// This 'INPUT' is goto LABEL.

INPUT:

// Take the input from the user

// Store them in 'x' and 'y' variables.

printf("Enter two Number : ");

scanf("%d%d", &x, &y);

// Take the operator from the user

char op;

printf("Enter the Operator [ +, -, *, /, %%] : ");

scanf(" %c", &op);

// Let's use the 'switch statement' to find operation

switch (op)

case '+':

// Operator is Addition ('+')

printf("Addition: %d + %d = %d \n", x, y, x+y);

break;

case '-':

// Subtraction ('-')

printf("Subtraction: %d - %d = %d \n", x, y, x-y);

break;

case '*':
// Product/Mutliplication ('*')

printf("Product: %d * %d = %d \n", x, y, x*y);

break;

case '/':

// Division ('/')

printf("Division: %d / %d = %d \n", x, y, x/y);

break;

case '%':

// Modulo division ('%')

printf("Modulo Division: %d %% %d = %d \n", x, y, x%y);

break;

default:

// Display the Error

printf("ERROR: Invalid Operation, Please try again\n");

// Let's use the goto statement to

// Take the control back to Operator input statement

goto INPUT;

break;

return 0;

Program Output:
We are using the GCC Compiler to compile and run the program.
$ gcc arithmetic-operations-switch.c
The gcc compiler by default generates the executable file with the a.out Name. So we are
going to run the a.out using the ./a.out command. ( As we are in the same directory as
where the file is located )
Example 1: Addition test case:
1$ ./a.out

2Enter two Number : 50 100

3Enter the Operator [ +, -, *, /, %] : +

4Addition: 50 + 100 = 150

Example 2: Subtraction:
1$ ./a.out

2Enter two Number : 30 10

3Enter the Operator [ +, -, *, /, %] : -

4Subtraction: 30 - 10 = 20

More Tests: Example 3: Multiplication, Division, and Modulo division:


1$ ./a.out

2Enter two Number : 20 50

3Enter the Operator [ +, -, *, /, %] : *

4Product: 20 * 50 = 1000

5$ ./a.out

6Enter two Number : 25 5

7Enter the Operator [ +, -, *, /, %] : /

8Division: 25 / 5 = 5

9$ ./a.out

10Enter two Number : 20 3

11Enter the Operator [ +, -, *, /, %] : %

12Modulo Division: 20 % 3 = 2

13$

Example 4: If user enters the wrong number:


1$ ./a.out

2Enter two Number : #

3Enter the Operator [ +, -, *, /, %] : ERROR: Invalid Operation, Please try again

4Enter two Number : 70 20

5Enter the Operator [ +, -, *, /, %] : %

6Modulo Division: 70 % 20 = 10

7$
Example 5: If the user enters the wrong Operator:
1$ ./a.out

2Enter two Number : 60 20

3Enter the Operator [ +, -, *, /, %] : &

4ERROR: Invalid Operation, Please try again

5Enter two Number : 60 20

6Enter the Operator [ +, -, *, /, %] : +

7Addition: 60 + 20 = 80

8$

Method 2: C Program to Perform arithmetic


operations Algorithm using if else ladder
Statement:
The Program logic is the same as the above method, We are going to take the two
numbers and the operator from the user. Now instead of using the switch statement,
We are going to use the if else ladder.
So We are going to compare the operator op with arithmetic operations ( addition,
subtraction, etc) using the condition like if(op == '+') , if (op == '-'), etc.
If the op is not equal to any of the operations, Then the final else statement will be
executed, where we are handling the Invalid Input case.

Program Arithmetic Operations with if else


ladder:
1/*

2 Program: C Program to perform arithmetic operations using if else ladder

3*/

5#include<stdio.h>

6int main() {

8 int x, y;

9
10 // If user provides wrong operator, we are using goto statement

11 // This 'INPUT' is goto LABEL.

12 INPUT:

13

14 // Take the input from the user

15 // Store them in 'x' and 'y' variables.

16 printf("Enter two Number : ");

17 scanf("%d%d", &x, &y);

18

19

20 // Take the operator from the user

21 char op;

22 printf("Enter the Operator [ +, -, *, /, %%] : ");

23 scanf(" %c", &op);

24

25 // Let's use the 'if else ladder' to compare the operator

26

27 if(op == '+')

28 {

29 // Operator is Addition ('+')

30 printf("Addition: %d + %d = %d \n", x, y, x+y);

31 }

32 else if (op == '-')

33 {

34 // Subtraction ('-')

35 printf("Subtraction: %d - %d = %d \n", x, y, x-y);

36 }

37 else if (op == '*')

38 {

39 // Product/Mutliplication ('*')
40 printf("Product: %d * %d = %d \n", x, y, x*y);

41 }

42 else if (op == '/')

43 {

44 // Division ('/')

45 printf("Division: %d / %d = %d \n", x, y, x/y);

46 }

47 else if (op == '%')

48 {

49 // Modulo division ('%')

50 printf("Modulo Division: %d %% %d = %d \n", x, y, x%y);

51 }

52 else{

53 // Display the Error

54 printf("ERROR: Invalid Operation, Please try again\n");

55

56 // Let's use the goto statement to

57 // Take the control back to Operator input statement

58 goto INPUT;

59 }

60

61 return 0;

62}

Program Output:
1$ gcc arithmetic-operations-if-else-ladder.c

2$ ./a.out

3Enter two Number : 80 70

4Enter the Operator [ +, -, *, /, %] : -

5Subtraction: 80 - 70 = 10
6$ ./a.out

7Enter two Number : 4 9

8Enter the Operator [ +, -, *, /, %] : *

9Product: 4 * 9 = 36

10$ ./a.out

11Enter two Number : 45 7

12Enter the Operator [ +, -, *, /, %] : /

13Division: 45 / 7 = 6

14$ ./a.out

15Enter two Number : 30 4

16Enter the Operator [ +, -, *, /, %] : %

17Modulo Division: 30 % 4 = 2

18$ ./a.out

19Enter two Number : 30 40

20Enter the Operator [ +, -, *, /, %] : +

21Addition: 30 + 40 = 70

22$ ./a.out

23Enter two Number : 90 10

24Enter the Operator [ +, -, *, /, %] : &

25ERROR: Invalid Operation, Please try again

26Enter two Number : 90 10

27Enter the Operator [ +, -, *, /, %] : @

28ERROR: Invalid Operation, Please try again

29Enter two Number : 90 10

30Enter the Operator [ +, -, *, /, %] : %

31Modulo Division: 90 % 10 = 0

32$

Algorithm to convert infix to postfix program in C

1. Start scanning the given expression from left to right.


2. If the scanned character is an operand, just print it.

3. Else

• If the precedence of the operand is higher than the precedence of the


operator the stack(or stack is empty or has'(‘), then push the operator in the
stack.

• Else, Pop all the operators, that have greater or equal precedence than the
scanned operator. Once you pop them push this scanned operator. (If we
see a parenthesis while popping then stop and push the scanned operator
in the stack)

4. If the scanned character is an ‘(‘, push it to the stack.

5. If the scanned character is an ‘)’, pop the stack and output it until a ‘(‘ is
encountered, and discard both the parenthesis.

6. Now, we should repeat steps 2 – 6 until the whole infix i.e. whole characters are
scanned.

7. Print output

8. Do the pop and output (print) until the stack is not empty
Method 1: Array-based stack approach to Convert Infix to Postfix

In this method, we will implement an array-based stack approach.

Code Implementation in C to Convert Infix to Postfix:

• C

#include <limits.h>

#include <stdio.h>

#include <stdlib.h>

#define MAX 20

char stk[20];

int top = -1;

int isEmpty(){
return top == -1;

int isFull(){

return top == MAX - 1;

char peek(){

return stk[top];

char pop(){

if(isEmpty())

return -1;

char ch = stk[top];

top--;

return(ch);

void push(char oper){

if(isFull())

printf("Stack Full!!!!");

else{

top++;
stk[top] = oper;

int checkIfOperand(char ch)

return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');

int precedence(char ch)

switch (ch)

case '+':

case '-':

return 1;

case '*':

case '/':

return 2;

case '^':

return 3;

return -1;
}

int covertInfixToPostfix(char* expression)

int i, j;

for (i = 0, j = -1; expression[i]; ++i)

if (checkIfOperand(expression[i]))

expression[++j] = expression[i];

else if (expression[i] == '(')

push(expression[i]);

else if (expression[i] == ')')

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

expression[++j] = pop();

if (!isEmpty() && peek() != '(')

return -1; // invalid expression

else

pop();

else // if an opertor

{
while (!isEmpty() && precedence(expression[i]) <= precedence(peek()))

expression[++j] = pop();

push(expression[i]);

while (!isEmpty())

expression[++j] = pop();

expression[++j] = '\0';

printf( "%s", expression);

int main()

char expression[] = "((p+(q*r))-s)";

covertInfixToPostfix(expression);

return 0;

Output: pqr*+s-

To start writing the program, use: vi example.l


This opens the vi editor. Here are some basic vi commands: Rookie's guide!
You can replace "example.l" with your own file name, of course. Don't forget the ".l" extension though!

5. Compile your lex program as:

lex example.l
gcc lex.yy.c -ll -o example
./example
This compiles the program, links the lex libraries with it, and renames the output file. Notice that we're using "gcc" - lex is
basically a C program!

6. You can start your yacc program similarly


vi example.y

7. To compile the lex and the yacc programs together (assuming that lex tokenizes the input and passes the tokens to
yacc)

lex example.l
yacc -d example.y
gcc lex.yy.c y.tab.c -ll -ly -o example
./example

Termwork 01:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<conio.h>
#define max 100
//main class
int main()
{
char str[max];
int f=1; //state
int i;
// reading the string to be checkeed from the user//
printf("\nENTER THE STREAM OF INPUT SYMBOLS:\n");
scanf("%s",str);
//char f='str'; //state
//printf("Input Taken");
//for statement start
for(i=0;str[i]!='\0';i++)
{
printf("%c",f);
//printf("For loop");
switch(f)
{
printf("Inside switch\n");
//first state
case 1:
if(str[i]=='a')
{
f=3;
printf("PROCESSING a and further checking for next symbols");
}
else if(str[i]=='.')
{
f=8;
}
else
{
//printf("\nOther symbol\n");
f=2;
}
break;
case 2:
if(str[i]== '.')
{
f=8;
}
else if(str[i]=='c')
{
printf("PROCESSING c and further checking for next symbols");
f=4;
}
else
{
f=2;
}
break;
case 3:
if(str[i]=='.')
{
f=8;
}
else if(str[i]=='/')
{
printf("\nPROCESSING '/' and further checking for next symbols\n");
f=5;
}
else
{
f=6;
}
break;
case 4:
if(str[i]=='.')
{
f=8;
}
else if(str[i]=='#')
{
printf("\n # Detected\n");
//printf("\nPATTERN FOUND\n");
f=6;
}
else
{
f=2;
}
break;
case 5:
if(str[i]=='.')
{
f=8;
}
else if(str[i]=='#')
{
printf("\nPATTERN FOUND\n");
f=2;
}
else
{
f=2;
}
break;
case 6:
if(str[i]=='.')
{
printf("\nPROGRAM HALTED AS '.' APPERAED\n");
exit(0);
}
else
{
f=1;
}
break;
case 'default':
printf("No Input detected");
}//end of switch
}//end of for loop
return 0;
}

USING GOTO
#include <stdio.h>
#include <string.h>
#define max 100
//main class
int main()
{
char str[max];
char f='a';//state
int i;
// reading the string to be checkeed from the user//
printf("ENTER THE STRING : ");
scanf("%s",str);

//for statement start


for(i=0; str[i]!='\0'; i++) {
//switch starts
//printf("start");
switch(f) {
//first state
case 'a':
if(str[i]=='1') {
f='c';
//printf("Yes 1 ");
}

else if(str[i]=='!' || str[i]=='@' || str[i]=='$' || str[i]=='&') {


//printf("special");
f='a';
printf("ERROR in input\n");
} else if (str[i]=='.') {
f='b';
printf("Program halted\n");
break;
} else if (str[i]=='b')
f='e';
else f='a';
break;
//---------------------------------------------------------------------------------
--------//
//second state 'b' is a
case 'b':
printf("Program halted\n");
break;
//---------------------------------------------------------------------------------
--------//
//third state c
case 'c':
if(str[i]=='1') {
f='d';
} else if(str[i]=='!' || str[i]=='@' || str[i]=='$' || str[i]=='&') {
f='a';
printf("ERROR in input\n");
}

else if (str[i]=='.') {
f='b';
printf("Program halted\n");
break;
} else if (str[i]=='b')
f='e';
else f='a';
break;
//---------------------------------------------------------------------------------
--------//
//fourth state d
case 'd' :
if(str[i]=='1') {
f='d';
printf("Ok\n");
}
else if(str[i]=='!' || str[i]=='@' || str[i]=='$' || str[i]=='&') {
f='a';
printf("ERROR in input\n");
} else if (str[i]=='.') {
f='b';
printf("Program halted\n");
break;
}

else if (str[i]=='b')
f='e';
else f='a';
break;
//---------------------------------------------------------------------------------
--------//
//fifth state e
case 'e':
if(str[i]=='1') {
f='c';
} else if(str[i]=='!' || str[i]=='@' || str[i]=='$' || str[i]=='&') {
f='a';
printf("ERROR in input\n");
}

else if (str[i]=='.') {
f='b';
printf("Program halted\n");
break;
}

else if (str[i]=='b')
f='f';
else f='a';
break;

//---------------------------------------------------------------------------------
--------//

//sixth state f
case 'f':
if(str[i]=='1') {
f='c';
} else if(str[i]=='!' || str[i]=='@' || str[i]=='$' || str[i]=='&') {
f='a';
printf("ERROR in input\n");
}

else if (str[i]=='.') {
f='b';
printf("Program halted\n");
break;
}

else if (str[i]=='b')
f='f';

else if(str[i]=='#')
f='g';
else f='a';
break;

//---------------------------------------------------------------------------------
--------//

//seventh state 'g'


case 'g':
if(str[i]=='1') {
f='c';
} else if(str[i]=='!' || str[i]=='@' || str[i]=='$' || str[i]=='&') {
f='a';
printf("ERROR in input\n");
}

else if (str[i]=='.') {
f='b';
printf("Program halted\n");
break;
}

else if (str[i]=='b')
f='e';

else if(str[i]==';') {
f='h';
printf("FOUND special\n");
} else f='a';

break;
} //end of switch
}//end of for
return 0;
}

#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
int main()
{
char ch;
goto s0;
s0:
printf("enter the characters:\n");
ch=getchar();
if(ch=='.')
exit(0);
else if(ch=='b')
goto s3;
else if(ch=='#' || ch=='!' || ch=='$')
{
printf("Error in Input\n");
goto s0;
}
else if(ch=='1')
goto s1;
else
goto s0;
s1:
ch=getchar();
if(ch=='.')
exit(0);
else if(ch=='b')
goto s3;
else if(ch=='1')
{
printf("ok 1 \n");
goto s2;
}
else if(ch=='#'||ch=='!'||ch=='&'||ch=='$')
{
printf("Error\n");
goto s0;
}
else
goto s0;
s2:
ch=getchar();
if(ch=='.')
exit(0);
else if(ch =='b')
goto s3;
else if(ch=='1')
{
printf("ok2\n");
goto s2;
}
else if(ch=='#'||ch=='!'||ch=='&'||ch=='$')
{
printf("Error\n");
goto s0;
}
else
goto s0;
s3:
ch=getchar();
if(ch=='.')
exit(0);
else if(ch=='b')
goto s4;
else if(ch=='1')
{
goto s1;
}
else if(ch=='@'||ch=='&'||ch=='$')
{
printf("Error\n");
goto s0;
}
else
goto s0;
s4:
ch=getchar();
if(ch=='.')
exit(0);
else if(ch=='b')
goto s3;
else if(ch=='#')
goto s5;
else if(ch=='1')
{
goto s1;
}
else if(ch=='@'||ch=='&'||ch=='$')
{
printf("Error\n");
goto s0;
}
else
goto s0;
s5:
ch=getchar();
if(ch=='.')
exit(0);
else if(ch=='b')
goto s3;
else if(ch=='#')
goto s0;
else if(ch='!'){
printf("Special case\n");
goto s0;
}
else if(ch=='1')
{
goto s1;
}
else if(ch=='@'||ch=='&'||ch=='$')
{
printf("Error\n");
goto s0;
}
else
{
goto s0;
}
return 0;
}

/* This program converts infix expression to postfix expression.


* This program assume that there are Five operators: (*, /, +, -,^)
in infix expression and operands can be of single-digit only.
* This program will not work for fractional numbers.
* Further this program does not check whether infix expression is
valid or not in terms of number of operators and operands.*/

#include<stdio.h>
#include<stdlib.h> /* for exit() */
#include<ctype.h> /* for isdigit(char ) */
#include<string.h>

#define SIZE 100

/* declared here as global variable because stack[]


* is used by more than one fucntions */
char stack[SIZE];
int top = -1;

/* define push operation */

void push(char item)


{
if(top >= SIZE-1)
{
printf("\nStack Overflow.");
}
else
{
top = top+1;
stack[top] = item;
}
}

/* define pop operation */


char pop()
{
char item ;

if(top <0)
{
printf("stack under flow: invalid infix expression");
getchar();
/* underflow may occur for invalid expression */
/* where ( and ) are not matched */
exit(1);
}
else
{
item = stack[top];
top = top-1;
return(item);
}
}

/* define function that is used to determine whether any symbol is operator or not
(that is symbol is operand)
* this fucntion returns 1 if symbol is opreator else return 0 */

int is_operator(char symbol)


{
if(symbol == '^' || symbol == '*' || symbol == '/' || symbol == '+' ||
symbol =='-')
{
return 1;
}
else
{
return 0;
}
}

/* define fucntion that is used to assign precendence to operator.


* Here ^ denotes exponent operator.
* In this fucntion we assume that higher integer value
* means higher precendence */

int precedence(char symbol)


{
if(symbol == '^')/* exponent operator, highest precedence*/
{
return(3);
}
else if(symbol == '*' || symbol == '/')
{
return(2);
}
else if(symbol == '+' || symbol == '-') /* lowest precedence */
{
return(1);
}
else
{
return(0);
}
}

void InfixToPostfix(char infix_exp[], char postfix_exp[])


{
int i, j;
char item;
char x;

push('('); /* push '(' onto stack */


strcat(infix_exp,")"); /* add ')' to infix expression */

i=0;
j=0;
item=infix_exp[i]; /* initialize before loop*/
while(item != '\0') /* run loop till end of infix expression */
{
if(item == '(')
{
push(item);
}
else if( isdigit(item) || isalpha(item))
{
postfix_exp[j] = item; /* add operand symbol to postfix expr
*/
j++;
}
else if(is_operator(item) == 1) /* means symbol is operator */
{
x=pop();
while(is_operator(x) == 1 && precedence(x)>= precedence(item))
{
postfix_exp[j] = x; /* so pop all higher precendence
operator and */
j++;
x = pop(); /* add them to postfix expresion */
}
push(x);
/* because just above while loop will terminate we have
oppped one extra item
for which condition fails and loop terminates, so that one*/

push(item); /* push current oprerator symbol onto stack */


}
else if(item == ')') /* if current symbol is ')' then */
{
x = pop(); /* pop and keep popping until */
while(x != '(') /* '(' encounterd */
{
postfix_exp[j] = x;
j++;
x = pop();
}
}
else
{ /* if current symbol is neither operand not '(' nor ')' and nor
operator */
printf("\nInvalid infix Expression.\n"); /* thus it is illegeal
symbol */
getchar();
exit(1);
}
i++;

item = infix_exp[i]; /* go to next symbol of infix expression */


} /* while loop ends here */
if(top>0)
{
printf("\nInvalid infix Expression.\n"); /* the it is illegeal
symbol */
getchar();
exit(1);
}
if(top>0)
{
printf("\nInvalid infix Expression.\n"); /* the it is illegeal
symbol */
getchar();
exit(1);
}

postfix_exp[j] = '\0'; /* add sentinel else puts() fucntion */


/* will print entire postfix[] array upto SIZE */

/* main function begins */


int main()
{
char infix[SIZE], postfix[SIZE]; /* declare infix string and
postfix string */

printf("ASSUMPTION: The infix expression contains single letter variables


and single digit constants only.\n");
printf("\nEnter Infix expression : ");
gets(infix);

InfixToPostfix(infix,postfix); /* call to convert */


printf("Postfix Expression: ");
puts(postfix); /* print postfix expression */

return 0;
}

You might also like