Thursday, 24 July 2014

DS Programme

/*
Translate Infix to postfix notation using stack.
s= (a*b+d)-(e*f^g^h)^i
--> ab*d+efg^h^*i^-
*/
#include<stdio.h>
#include<conio.h>
void main()
{
   char in[50],stk[50];
   int i,top=-1;
   clrscr();
   printf ("\n \t  Enter a Infix Notation:");
   gets(in);
   stk[++top]='(';
   printf("\n \t Postfix :");
   for(i=0;in[i]!='\0';i++)
   {
   switch(in[i])
   {
     case '(' :  stk[++top]='(';
  break;
     case ')' :   while(stk[top]!='(')
  {
      printf("%c",stk[top--]);
  }
  top--;
  break;
     case '^' :   while(stk[top]=='^')
  {
      printf("%c",stk[top--]);
  }
  stk[++top]=in[i];
  break;
     case '*' :
     case '/' :
while(stk[top]=='^' || stk[top]=='*' || stk[top]=='/')
  {
      printf("%c",stk[top--]);
  }
  stk[++top]=in[i];
  break;
     case '+' :
     case '-' :
  while(stk[top]=='^' || stk[top]=='*' || stk[top]=='/'  || stk[top]=='+' || stk[top]=='-'  )
  {
      printf("%c",stk[top--]);
  }
  stk[++top]=in[i];
  break;
     default :
       printf("%c",in[i]);
break;
    }
  }
  while(stk[top]!='(')
  {
      printf("%c",stk[top--]);
  }
  getch();
}
###########=jbvaghasiya====================================================

/*
Translate Infix to prefix notation using stack.
s= a+b+c
--> ++abc
*/
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
   char in[50],stk[50],pre[50];
   int i,top=-1,k=0;
   clrscr();
   printf ("\n \t  Enter a Infix Notation:");
   gets(in);
   stk[++top]=')';

   for(i=strlen(in)-1;i>=0;i--)
   {
   switch(in[i])
   {
     case '(' :
while(stk[top]!=')')
  {
   pre[k++]=stk[top--];
  }
  top--;
  break;
     case ')' :   stk[++top]=')';
  break;
     case '^' :
  stk[++top]=in[i];
  break;
     case '*' :
     case '/' :
while(stk[top]=='^')
  {
   pre[k++]=stk[top--];
  }
  stk[++top]=in[i];
  break;
     case '+' :
     case '-' :
  while(stk[top]=='^' || stk[top]=='*' || stk[top]=='/')
  {
     pre[k++]=stk[top--];
  }
  stk[++top]=in[i];
  break;
     default :
pre[k++]=in[i];
break;
    }
  }
  while(stk[top]!=')')
  {
      pre[k++]=stk[top--];
  }
//       strrev(pre);
printf("\n \t Prefix :");
       for(i=strlen(pre)-1;i>=0;i--)
   printf("%c",pre[i]);
  getch();
}

J.b.vaghasiya

No comments:

Post a Comment