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

LR

The document is a C program that implements a simple LR parsing algorithm for arithmetic expressions. It uses a stack to manage operators and operands, specifically handling the terminal 'id' and non-terminal 'E'. The program reads an expression, processes it, and outputs the state of the stack at various stages.

Uploaded by

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

LR

The document is a C program that implements a simple LR parsing algorithm for arithmetic expressions. It uses a stack to manage operators and operands, specifically handling the terminal 'id' and non-terminal 'E'. The program reads an expression, processes it, and outputs the state of the stack at various stages.

Uploaded by

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

#include <stdio.

h>

#include <string.h>

#include <stdlib.h>

char stack[30];

int top = -1;

void push(char c) {

top++;

stack[top] = c;

char pop() {

char c;

if (top != -1) {

c = stack[top];

top--;

return c;

return 'x'; // Return 'x' if the stack is empty

void printstat() {

int i;

printf("\n\t\t\t $");
for (i = 0; i <= top; i++)

printf("%c", stack[i]);

void main() {

int i, j, l;

char s1[20], ch1, ch2, ch3;

printf("\n\n\t\t LR PARSING");

printf("\n\t\t ENTER THE EXPRESSION: ");

scanf("%s", s1);

l = strlen(s1);

printf("\n\t\t $");

for (i = 0; i < l; i++) {

if (s1[i] == 'i' && s1[i + 1] == 'd') { // Assume 'id' is a terminal

s1[i] = ' '; // Replace 'id' with a space

s1[i + 1] = 'E'; // Map 'id' to non-terminal 'E'

printstat();

printf(" id");

push('E'); // Push non-terminal onto the stack

printstat();

} else if (s1[i] == '+' || s1[i] == '-' || s1[i] == '*' || s1[i] == '/') {

push(s1[i]); // Push operator onto the stack


printstat();

printstat();

// Process the stack until it's empty

while (top >= 0) {

ch1 = pop();

if (ch1 == 'x') { // If the stack is empty

printf("\n\t\t\t $");

break;

if (ch1 == '+' || ch1 == '/' || ch1 == '*' || ch1 == '-') {

ch3 = pop();

if (ch3 != 'E') { // Check if the top of the stack is 'E'

printf("error");

exit(1);

} else {

push('E'); // If 'E' is found, push it back

printstat();

}
ch2 = ch1; // Assign for future operations

}
Output:

LR PARSING

ENTER THE EXPRESSION: id*id+id

$ id

$E

$E*

$E* id

$E*E

$E*E+

$E*E+ id

$E*E+E

$E*E+E

$E*E

$E

You might also like