0% found this document useful (0 votes)
11 views

Executed Programs II Sem

The document contains C code examples demonstrating various data structures and algorithms, including: 1. Call by value and call by reference functions to swap integer values. 2. Implementations of sorting algorithms like insertion sort, selection sort, bubble sort, quicksort, merge sort using arrays. 3. Search algorithms like linear search and binary search to find an element in a sorted array. 4. Other examples using pointers to find string length, concatenate strings, copy strings. 5. Array implementations of stacks and queues with push, pop, display functions for stacks and insert, delete, display for queues.

Uploaded by

Sswetha Sara
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Executed Programs II Sem

The document contains C code examples demonstrating various data structures and algorithms, including: 1. Call by value and call by reference functions to swap integer values. 2. Implementations of sorting algorithms like insertion sort, selection sort, bubble sort, quicksort, merge sort using arrays. 3. Search algorithms like linear search and binary search to find an element in a sorted array. 4. Other examples using pointers to find string length, concatenate strings, copy strings. 5. Array implementations of stacks and queues with push, pop, display functions for stacks and insert, delete, display for queues.

Uploaded by

Sswetha Sara
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Executed programs:

1. Call by value and call by reference:


#include <stdio.h>
void main()
{
int a,b;
void swap_val(int , int );
void swap_ref(int *, int * );
printf("Enter two numbers \n");
scanf("%d %d",&a,&b);
printf("a =%d b = %d before function \n",a,b);
swap_val(a,b);
printf("a =%d b = %d after function call using call by value \n",a, b);
swap_ref(&a,&b);
printf("a =%d b = %d after function call using call by reference \n",a,b);
}
/* Function to exchange two values using call by value */
void swap_val(int x, int y)
{
int temp;
temp = x;
x = y;
y = temp;
}
/* Function to exchange two values using call by reference */
void swap_ref(int *x, int * y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
Insertion sort
#include <stdio.h>
void main( )
{
int a[100], n;
int i, j, temp;
printf("\nEnter number of elements \n");
scanf("%d",&n);
printf("\nEnter array elements\n");
for( i=0 ; i<n ; i++ )
scanf("%d",&a[i]);
printf("\The unsorted list is\n");
for( i=0 ; i<n ; i++ )
printf("\t%d",a[i]);
printf("\n");
for(i =1; i < n ; i++ )
{
j = i;
while ( j >= 1)
{
if(a [j] < a [j-1] )
{
temp = a[j];
a[j] = a[j-1];
a[j-1]= temp;
}
j = j -1 ;
}
}
printf("\nThe sorted list is \n");
for( i=0 ; i<n ; i++ )
printf(" %d\n ",a[i]);
printf("\n");
}

Selection Sort
#include <stdio.h>
void main( )
{
int a[100], n;
int i, j, small, pos;
printf("\nEnter number of elements\n");
scanf("%d",&n);
printf("\nEnter array elements\n");
for( i=0 ; i<n ; i++ )
scanf("%d",&a[i]);
printf("\nThe unsorted list is\n");
for( i=0 ; i<n ; i++ )
printf("\t%d",a[i]);
printf("\n");
for(i = 0; i < n-1 ; i++)
{
small = a[i];
pos = i;
for(j=i+1 ;j<n ;j ++)
if(a[j] < small)
{
small=a[j];
pos = j;
}
a[pos] = a[i];
a[i] = small;
}
printf("\n The sorted list is \n");
for( i=0 ; i<n ; i++ )
printf("\t%d",a[i]);
printf("\n");
}

Bubble sort
#include <stdio.h>
void main( )
{
int a[100], n;
int i, j, temp;
printf("\nEnter number of elements\n");
scanf("%d",&n);
printf("\nEnter array elements\n");
for( i=0 ; i<n ; i++ )
scanf("%d",&a[i]);
printf("\nThe unsorted list is\n");
for( i=0 ; i<n ; i++ )
printf("\t%d",a[i]);
printf("\n");
for(i = 0; i < n ; i++)
for(j=0 ;j<n-i ;j ++)
if(a[j] > a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1]=temp;
}
printf("\n The sorted list is \n");
for( i=1 ; i<=n ; i++ )
printf("\t%d",a[i]);
printf("\n");
}
Quick sort
#include <stdio.h>
void quicksort(int* , int, int);
void partition(int*, int, int, int* );
void main( )
{
int a[20], n, i;
printf("Enter the number of elements \n");
scanf("%d",&n);
printf("Enter %d elements \n",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("The UnSorted elements are\n");
for(i=0;i<n;i++)
printf("\t%d",a[i]);
printf("\n");
quicksort( a, 0, n-1 );
printf("The Sorted elements are\n");
for(i=0;i<n;i++)
printf("\t%d",a[i]);
printf("\n");
}
/* Recursive Quick sort function */void quicksort(int a[], int low, int
high)
{
int pos;
if ( low < high )
{
partition( a , low , high, &pos);
quicksort( a , low, pos -1 );
quicksort( a , pos + 1, high);
}
}
/* Function to create partitions */
void partition (int a[], int low, int high, int *p)
{
int x, up, down,temp;
x = a[low] ;
up = high;
down = low ;
while ( down < up )
{
while ( (a [ down] <= x) && ( down < high ))
down = down + 1 ;
while ( a [ up] > x)
up = up - 1;
if ( down < up )
{
temp = a [ down ];
a [ down ] = a[ up];
a [ up] = temp;
}
}
a [ low ] = a [ up ];
a [ up ] = x;
*p = up;
}

Merge Sort
#include <stdio.h>
void mergesort( int*, int, int);
void merge( int*, int, int, int );
void main( )
{
int a[20], n, i;
printf("\nEnter the number of elements\n");
scanf("%d",&n);
printf("\nEnter %d elements \n",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\nThe UnSorted elements are\n");
for(i = 0; i < n;i++)
printf("\t%d",a[i]);
printf("\n");
mergesort(a, 0, n-1);
printf("\nThe Sorted elements are\n");
for(i = 0;i < n; i++)
printf("\t%d",a[i]);
printf("\n");
}
/* Merge_sort function */
void mergesort(int a[ ], int low, int high)
{
int mid;
if ( low < high )
{
mid = (low + high) /2;
mergesort( a , low, mid );
mergesort( a , mid + 1, high);
merge(a,low,mid,high);
}
}
/* Merge function */
void merge (int a[], int low, int mid, int high)
{ int i, j, k,c[20];
i = low ;
k = low;
j = mid + 1 ;
while ( ( i <=mid) && ( j <= high))
{
if ( a[i] < a[j] )
{
c[k] = a[i];
k++;
i++;
}
else
{
c[k] = a[j];
k++;
j++;
}
}
while ( i <= mid)
{
c[k] = a[i];
k++;
i++;
}
while ( j <= high)
{
c[k] = a[j];
k++;
j++;
}
for ( i = low; i <= k-1; i++)
a[i]= c[i];
}

Linear search
#include <stdio.h>
int Linear_search( int* , int , int );
void main( )
{
int a[100], ele, pos, n, i;
printf("\nEnter the size of the array :\n");
scanf("%d",&n);
printf("\nEnter %d elements\n",n);
for(i = 0 ; i < n ; i ++)
scanf("%d", &a[i]);
printf("\nEnter element to search :\n");
scanf("%d",&ele);
pos= Linear_search(a, ele,n);
if ( pos == -1)
printf("\nElement not present");
else
printf("\nElement found in position : %d", pos);
}
/* Function to search an item using linear search technique */
int Linear_search( int a [ ] , int e, int m)
{
int i;
for(i = 0 ; i < m ; i ++)
if ( a[i]==e )
return(i+1); return(-1);
}

Binary Search
#include <stdio.h>
int Binary_search( int *, int , int );
void main( )
{
int a[100], ele, pos, n, i;
printf("\n Enter the array size \n");
scanf("%d",&n);
printf("\n Enter %d elements in sorted order\n",n);
for(i = 0 ; i < n ; i ++)
scanf("%d", &a[i]);
printf("Enter the element to search\n");
scanf("%d",&ele);
pos= Binary_search(a, ele,n);
if ( pos == -1)
printf("Element not present \n");
else
printf("Element found in position :%d\n", pos);
}
/* Function to perform Binary search */
int Binary_search( int a [ ] , int e, int m)
{
int low, high, mid;
low = 0;
high = m - 1;
while (low <= high)
{
mid = (low + high) / 2;
if (e == a[mid])
return(mid+1);
if (e < a[mid])
high = mid - 1;
else
low = mid + 1;
}
return(-1);
}

Length of string using Pointers:


#include <stdio.h>
void main( )
{
char str[50];
char *sptr;
int length;
printf("Enter a string\n");
scanf("%s",str);
sptr = str; /* assigns the address of first character of str */
printf("\nEntered string: \n");
while(*sptr!='\0')
{
printf("%c",*sptr);
sptr++;
}
length = sptr-str;
printf("\nLength of the string = %d",length);
}

Concatenate two strings using pointers:


#include <stdio.h>
int main()
{
char aa[100], bb[100]; printf("\nEnter the first string: "); gets(aa);
// inputting first string
printf("\nEnter the second string to be concatenated: "); gets(bb); //
inputting second string
char *a = aa; char *b = bb;
// pointing to the end of the 1st string
while(*a!=0) // till it doesn't point to NULL-till string is not empty
{
a++; // point to the next letter of the string
}
while(*b) // till second string is not empty
{ *a = *b;
b++; a++;
}
printf("\n\n\nThe string after concatenation is: %s ", aa);
return 0;
}

Copy strings using pointers


#include<stdio.h>
void copy_string(char*, char*);
main()
{
char source[100], target[100]; printf("Enter source string\n");
gets(source);
copy_string(target, source);
printf("Target string is \"%s\"\n", target); return 0;
}
void copy_string(char *target, char *source)
{
while(*source)
{
*target = *source; source++;
target++;
}
*target = '\0';
}

Array implementation of stack


#include<stdio.h>
int stack[100],choice, n, top,x,i;
void push();
void pop();
void display();
int main()
{
//clrscr(); top=-1;
printf("\n Enter the size of STACK[MAX=100]:");
scanf("%d", &n);
printf("\n\t STACK OPERATIONS USING ARRAY");
printf("\n\t--------------------------------");
printf("\n\t 1.PUSH\n\t 2.POP\n\t 3.DISPLAY\n\t 4.EXIT"); do
{
printf("\n Enter the Choice:");
scanf("%d", &choice);
switch(choice)
{
case 1:
{
push();
break;
}
case 2:
{
pop(); break;
}
case 3:
{
display(); break;
}
case 4:
{
printf("\n\t EXIT POINT ");
break;
}
default:
{
printf ("\n\t Please Enter a Valid Choice(1/2/3/4)");
}
}
}
while(choice!=4);
return 0;
}
void push()
{
if(top>=n-1)
{
printf("\n\tSTACK over flow");
}
else
{
printf(" Enter a value to be pushed:"); scanf("%d",&x); top++;
stack[top]=x;
}
}
void pop()
{
if(top<=-1)
{
printf("\n\t Stack is under flow");
}
else
{
printf("\n\t The popped elements is %d",stack[top]); top--;
}
}
void display()
{
if(top>=0)
{
printf("\n The elements in STACK \n");
for(i=top; i>=0; i--) printf("\n%d",stack[i]);
printf("\n Press Next Choice");
}
else
{
printf("\n The STACK is empty");
}
}

Array implementation of Queue


#include<stdio.h>
#include<conio.h>
#include <stdlib.h>
#define MAX 5
void QINSERT(int); // function prototype to add an item
int QDELETE(); // function prototype to delete an item
void DISPLAY(); // function prototype to display items
static int FRONT=-1,REAR=-1; int Q[MAX];
/* Main Function */
void main()
{
int choice;
int item;
while(1)
{
printf("Queue Operations:\n");
printf(" 1. ADD \n");
printf(" 2. DELETE \n");
printf(" 3. DISPLAY Contents \n");
printf(" 4. Exit \n"); printf("Enter your choice: \n");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("Enter item to ADD: \n");
scanf("%d",&item);
QINSERT(item);
break;
case 2 :
item=QDELETE();
printf("Deleted item is : %d\n",item);
break;
case 3 :
printf("The QUEUE contents is:\n");
DISPLAY();
break;
case 4:
exit(0);
default : printf("Invalid choice!!!!!! \n");
getch();
}
}
}
/* Function to Add an item onto a Queue */
void QINSERT( int item )
{
int N= MAX;
if(REAR==N-1)
{
printf("Queue Overflow\n");
exit(0);
}
else
{
REAR++; // increment REAR by 1
Q[REAR]=item; if ( FRONT==-1) FRONT = 0; // Set FRONT to 0
}
}
/* Function to Remove an item onto a Queue */
int QDELETE()
{
int item;
if(FRONT==-1)
{
printf("Queue Underflow\n");
exit(0);
}
else
{
item = Q[FRONT];
if (FRONT == REAR) //Queue has only one element
{ FRONT = -1;
REAR = -1;
}
else // Increment FRONT pointer FRONT = FRONT + 1;
return (item);
}
}
void DISPLAY()
{
int i;
if(FRONT==-1)
printf("Empty Queue!!!!!!!!! \n");
else
for(i=FRONT; i<=REAR; i++)
printf("Q[%d] = %d \n ",i, Q[i]);
getch();
}

Array implementation of Circular Queue


#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#define MAX 5
void CQINSERT(int); // function prototype to add an item
int CQDELETE(); // function prototype to delete an item
void DISPLAY(); // function prototype to display items
static int FRONT=-1,REAR=-1; int CQ[MAX];
/* Main function */
void main()
{
int choice, item;
while(1)
{
printf("Circular Queue Operations:\n");
printf(" 1. ADD \n");
printf(" 2. DELETE \n");
printf(" 3. DISPLAY Contents \n");
printf(" 4. Exit \n");
printf("Enter your choice: \n");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("Enter item to ADD: \n");
scanf("%d",&item);
CQINSERT(item);
break; case 2 :
item=CQDELETE();
printf("Deleted item is : %d\n",item);
break;
case 3 :
printf("The CIRCULAR QUEUE contents is:\n");
DISPLAY();
break;
case 4:
exit(0);
default :
printf("Invalid choice!!!!!! \n");
getch();
}
}
}
/* Insert an item in a circular queue */
void CQINSERT(int item)
{
if((FRONT==0 && REAR==MAX-1)||(FRONT==(REAR)+1))
{
printf("Queue is full. Overflow!");
exit(0);
}
else
{
if(FRONT==-1) /* Empty queue */
{
FRONT=0;
REAR=0;
}
else if(REAR==MAX-1) REAR=0;
else
REAR++;
CQ[REAR]=item;
}
}
/* Delete an item from a circular queue */
int CQDELETE()
{
int item;
if(FRONT==-1) /* Empty queue */
{
printf("Queue is empty or Underflow!");
exit(0);
}
else
{
item=CQ[FRONT];
if(FRONT==REAR)
{
FRONT=-1;
REAR=-1;
}
else if(FRONT==MAX-1)FRONT=0; else
FRONT++;
return(item);
}
}
/* Function to display circular queue elements */
void DISPLAY()
{
int i=FRONT;
if(FRONT==-1 && REAR==-1)
{
printf("\n Queue is empty..");
} else
{
printf("\nElements in a Queue are :");
while(i<=REAR)
{
printf("%d,", CQ[i]);
i=(i+1)%MAX;
}
}
}
Create a link list
#include<stdio.h>
#include<stdlib.h>
struct NODE *currptr;
struct NODE
{
int data;
struct NODE *link;
}*HEAD;

void CREATE(int ele)


{
struct NODE *newnode, *currptr;
newnode=(struct NODE*)malloc(sizeof(struct NODE));
newnode->data=ele;
newnode->link=NULL;
if(HEAD==NULL)
HEAD=newnode;
else
{
currptr=HEAD;
while(currptr->link!=NULL)
currptr=currptr->link;
currptr->link = newnode;
}
}
void DISPLAY()
{
struct NODE *currptr;
currptr=HEAD;
while(currptr!=NULL)
{
printf("%d ",currptr->data);
currptr=currptr->link;
}
}
void main()
{
int ele,ch;
HEAD=NULL;
do
{
printf("\n Link list program\n");
printf("\n 1. Adding");
printf("\n 2. Display");
printf("\n 3. Exit");
printf("\n Enter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("Enter the data:\n");
scanf("%d",&ele);
CREATE(ele);
break;
case 2: DISPLAY();
break;
case 3: printf("\n You have Exit the program");
break;
}
}
while(ch!=3);
}

Create link list and add elements


#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <conio.h>
struct node
{
int info;
struct node *link;
};
typedef struct node NODE;
NODE *HEAD;
void Create_link_list(int);
void Display(NODE *);
void Insert_Beginning(int);
void Insert_End(int);
void Insert_Position(int,int);
void main()
{
int ele,pos;
int ch;
HEAD = NULL;
printf("\nLinked list creation\n\n");

do{
printf("Enter information field of the node\n");
scanf("%d",&ele);
Create_link_list(ele);

}while(toupper(ch)=='Y');
printf("\nThe linked list is \n");
Display(HEAD);
printf("\nInsert Operation\n\n");

do
{
printf("\nChoose Position To Insert: \n");printf("\n1. AT THE
BEGINING");
printf("\n2. AT THE END");
printf("\n3. AT A GIVEN POSITION");
printf("\n4. Display");
printf("\n5. EXIT");
printf("\n\nEnter your choice : ");
scanf("%d",&ch);

switch(ch)
{
case 1: {
printf("\nEnter element to add : ");
scanf("%d",&ele);
Insert_Beginning(ele);
printf("\nThe linked list is \n");
Display(HEAD);
break;
}
case 2: {
printf("\nEnter element to add : ");
scanf("%d",&ele);
Insert_End(ele);
printf("\nThe linked list is \n");
Display(HEAD);
break;
}
case 3: {
printf("\nEnter element to add : ");
scanf("%d",&ele);
printf("\nEnter position to add: ");
scanf("%d",&pos);
Insert_Position(ele,pos);
break;
}
case 4:
printf("\nThe linked list is \n");
Display(HEAD);
break;
}
}while(ch != 5);
}
/* Function to add a node to the linked list */
void Create_link_list(int ele)
{
NODE *NewNode,*CurrPtr;
NewNode=(NODE *)malloc(sizeof(NODE));
NewNode->info=ele;
NewNode->link=NULL;
if( HEAD==NULL)
HEAD=NewNode;
else
{
CurrPtr=HEAD;
while(CurrPtr->link!=NULL)
CurrPtr=CurrPtr->link;
CurrPtr->link=NewNode;
}
}
/* Function to display linked list elements */
void Display(NODE *CurrPtr)
{
printf("\n\n*********************************************\n");
CurrPtr=HEAD;
while(CurrPtr!=NULL)
{
printf("%d\t",CurrPtr->info);
CurrPtr=CurrPtr->link;
}
printf("NULL\n");
printf("*********************************************\n\n");
}
/* Function to insert a node at the beginning of the linked list */
void Insert_Beginning( int ITEM )
{
NODE *NewNode;
NewNode= (NODE *) malloc(sizeof(NODE));
NewNode->info=ITEM;
NewNode->link=HEAD;
HEAD = NewNode;
}
/* Function to insert a node at the end of the linked list */
void Insert_End (int ITEM)
{
NODE *NewNode, *CurrPtr;
NewNode= (NODE *) malloc(sizeof(NODE));
NewNode->info=ITEM;
NewNode->link=NULL;
CurrPtr=HEAD;

while(CurrPtr->link!=NULL)
CurrPtr=CurrPtr->link;
CurrPtr->link=NewNode;
}
/* Function to insert a node at a given position in a linked list */
void Insert_Position( int ITEM, int POS)
{
NODE *NewNode,*CurrPtr;
int i;
NewNode= (NODE *) malloc(sizeof(NODE));
NewNode->info=ITEM;
CurrPtr = HEAD;

for( i = 1; i< POS-1 && CurrPtr != NULL; i++)


CurrPtr = CurrPtr->link;

if ( CurrPtr ==NULL)
{
printf("Position Out Of Range\n");
exit(0);
}
NewNode->link = CurrPtr->link;
CurrPtr->link = NewNode;
}

Delete from a node


#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <ctype.h>
struct node
{
int info;
struct node *link;
};
typedef struct node NODE;
NODE *HEAD;
void Create_link_list(int);
void Display(NODE *);
int Delete_Beginning();
int Delete_End();
int Delete_Position(int);
int main( )
{
int ele,pos,n,i,n1;
char ch;
HEAD = NULL;
printf("Enter number of nodes to create ");
scanf("%d",&n);
printf("\nLinked list creation\n");
printf("Enter information field of the node\n");
for(i=0;i<n;i++)
{
scanf("%d",&ele);
Create_link_list(ele);
}
printf("\nThe linked list is \n");
Display(HEAD);
printf("\nDeletion Operation\n\n");
do
{
printf("\nChoose Position To Delete: \n");
printf("\n1. AT THE BEGINING");
printf("\n2. AT THE END");
printf("\n3. AT A GIVEN POSITION");
printf("\n4. EXIT");
printf("\n\nEnter your choice : ");
scanf("%d",&n1);
switch(n1)
{
case 1: {
ele = Delete_Beginning();
printf("\nDeleted element is :%d ",ele);
printf("\nThe linked list is \n ");
Display(HEAD);
break;
}
case 2: {
ele = Delete_End();
printf("\nDeleted element is :%d ",ele);
printf("\nThe linked list is \n ");
Display(HEAD);
break;
}
case 3: {
printf("\nEnter position to delete: ");
scanf("%d",&pos);
ele = Delete_Position(pos);
printf("\nDeleted element is :%d ",ele);
printf("\nThe linked list is \n ");
Display(HEAD);
break;
}
case 4: {printf("\n\tEXIT POINT");
exit(0);}
default: printf("Enter a valid number(1/2/3/4)");
}
}while(ch != 4);
getch();
}

void Create_link_list(int ele)


{
NODE *NewNode,*CurrPtr;
NewNode=(NODE *)malloc(sizeof(NODE));
NewNode->info=ele;
NewNode->link=NULL;
if( HEAD==NULL)
HEAD=NewNode;
else
{
CurrPtr=HEAD;
while(CurrPtr->link!=NULL)
CurrPtr=CurrPtr->link;
CurrPtr->link=NewNode;
}}

void Display(NODE *CurrPtr)


{ CurrPtr=HEAD;
while(CurrPtr!=NULL)
{
printf("%d ",CurrPtr->info);
CurrPtr=CurrPtr->link;
}
printf("NULL\n");
}

int Delete_Beginning( )
{
NODE *CurrPtr;
int ele;
if ( HEAD == NULL)
{
printf("\nDeletion not possible");
exit(0);
}
CurrPtr = HEAD;
ele = CurrPtr->info;
HEAD = CurrPtr->link;
free(CurrPtr);
return(ele);}

int Delete_End( )
{
NODE *CurrPtr,*PrevPtr;
int ele;
if ( HEAD == NULL)
{
printf("\nDeletion not possible");
exit(0);
}
CurrPtr = HEAD;
while ( CurrPtr->link != NULL)
{PrevPtr = CurrPtr;
CurrPtr = CurrPtr->link;
}
ele = CurrPtr->info;
PrevPtr->link = NULL;
free(CurrPtr);
return(ele);
}

int Delete_Position( int POS )


{
NODE *CurrPtr,*PrevPtr;
int ele,i;
if ( HEAD == NULL)
{
printf("\nDeletion not possible");
exit(0);
}
if (POS==1)
{
Delete_Beginning();
}
else
{
CurrPtr = HEAD;
for( i = 1; i< POS && CurrPtr != NULL; i++)
{
PrevPtr = CurrPtr;
CurrPtr = CurrPtr->link;
}
if ( CurrPtr == NULL)
{
printf("\nPositon out of range");
exit(0);
}
ele = CurrPtr->info;
PrevPtr->link = CurrPtr->link;
free(CurrPtr);
return(ele);
}
}
Infix to Postfix
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<stdlib.h>

#define BLANK ' '


#define TAB '\t'
#define MAX 50
void push(long int symbol);
long int pop();
void infix_to_postfix();
long int eval_post();
int priority(char symbol);
int isEmpty();
int white_space(char );
char infix[MAX], postfix[MAX];
long int stack[MAX];
int top;
int main()
{
long int value;
top=-1;
printf("Enter infix : ");
scanf("%s",infix);
infix_to_postfix();
printf("Postfix : %s\n",postfix);
value=eval_post();
printf("Value of expression : %ld\n",value);
return 0;
}
void infix_to_postfix()
{
unsigned int i,p=0;
char next;
char symbol;
for(i=0;i<strlen(infix);i++)
{
symbol=infix[i];
if(!white_space(symbol))
{
switch(symbol)
{
case '(':
push(symbol);
break;
case ')':
while((next=pop())!='(')
postfix[p++] = next;
break;
case '+':
case '-':
case '*':
case '/':
case '%':
case '^':
while( !isEmpty( ) &&
priority(stack[top])>= priority(symbol) )
postfix[p++]=pop();
push(symbol);
break;
default:
postfix[p++]=symbol;
}
}
}
while(!isEmpty( ))
postfix[p++]=pop();
postfix[p]='\0';
}
int priority(char symbol)
{
switch(symbol)
{
case '(':
return 0;
case '+':
case '-':
return 1;
case '*':
case '/':
case '%':
return 2;
case '^':
return 3;
default :
return 0;
}
}
void push(long int symbol)
{
if(top>MAX)
{
printf("Stack overflow\n");
exit(1);
}
stack[++top]=symbol;
}
long int pop()
{
if( isEmpty() )
{
printf("Stack underflow\n");
exit(1);
}
return (stack[top--]);
}
int isEmpty()
{
if(top==-1)
return 1;
else
return 0;
}
int white_space(char symbol)
{
if( symbol == BLANK || symbol == TAB )
return 1;
else
return 0;
}
long int eval_post()
{
long int a,b,temp,result;
unsigned int i;
for(i=0;i<strlen(postfix);i++)
{
if(postfix[i]<='9' && postfix[i]>='0')
push(postfix[i]-'0');
else
{
a=pop();
b=pop();
switch(postfix[i])
{
case '+':
temp=b+a; break;
case '-':
temp=b-a;break;
case '*':
temp=b*a;break;
case '/':
temp=b/a;break;
case '%':
temp=b%a;break;
case '^':
temp=pow(b,a);
}
push(temp);
}
}
result=pop();
return result;
}

You might also like