Search code examples
cpostfix-notation

Infix to Postfix, math function(sin), C


how i can implement math function(sin) to my easy Infix to Postfix convertor?

The code is from http://www.c-program-example.com/2011/10/c-program-for-infix-to-postfix.html

Its possible implement for example sin? Start expresion will be for example sin(2+3), or sin(3)+3....

Can you give me a example?

Thank you verry much.

int pr(char elem) { /* Function for precedence */
 switch (elem) {
 case '#':
  return 0;
 case '(':
  return 1;
 case '+':
 case '-':
  return 2;
 case '*':
 case '/':
  return 3;
 }
}

main() { /* Main Program */
 char infx[50], pofx[50], ch, elem;
 int i = 0, k = 0;
 printf("\n\nRead the Infix Expression ? ");
 scanf("%s", infx);
 push('#');
 while ((ch = infx[i++]) != '\0') {
  if (ch == '(')
   push(ch);
  else if (isalnum(ch))
   pofx[k++] = ch;
  else if (ch == ')') {
   while (s[top] != '(')
    pofx[k++] = pop();
   elem = pop(); /* Remove ( */
  } else { /* Operator */
   while (pr(s[top]) >= pr(ch))
    pofx[k++] = pop();
   push(ch);
  }
 }
.

. .

}

Solution

  • Provisionally, If you think of another name of sin the !.

    int pr(char elem) { /* Function for precedence */
     switch (elem) {
     case '#':
      return 0;
     case '(':
      return 1;
     case '+':
     case '-':
      return 2;
     case '*':
     case '/':
      return 3;
     case '!':
      return 4;
     }
    }
    

    execute : sin(2+3):

    Read the Infix Expression ? !(2+3)
    Given Infix Expn: !(2+3)  Postfix Expn: 23+!
    

    sin(3)+3

    Read the Infix Expression ? !(3)+3
    Given Infix Expn: !(3)+3  Postfix Expn: 3!3+
    

    So logic is good the same, but you will need to change to handle the input of string from single character.