home *** CD-ROM | disk | FTP | other *** search
/ The C Users' Group Library 1994 August / wc-cdrom-cusersgrouplibrary-1994-08.iso / vol_200 / 200_01 / calc.sci < prev    next >
Text File  |  1979-12-31  |  2KB  |  100 lines

  1. #
  2. # Sample infix notation calculator program for SCI (version 1.5)
  3. #
  4. char *Lineptr;
  5. int Stack[10], Stackptr, Stacktop;
  6.  
  7. calc()
  8. {
  9.    char line[80];
  10.  
  11.    Stacktop = 10;
  12.    for(;;)
  13.    {
  14.       puts("-> ");
  15.       if( gets(Lineptr=line) )
  16.       {
  17.          addition();
  18.          printf( "%d\n", pop() );
  19.       }
  20.       else
  21.          return;
  22.    }
  23. }
  24.  
  25. number()
  26. {
  27.    if( isdigit( *Lineptr ) )
  28.    {
  29.       push( atoi( Lineptr ) );
  30.       while( isdigit( *Lineptr ) )
  31.          ++Lineptr;
  32.    }
  33. }
  34.  
  35. addition()
  36. {
  37.    int num;
  38.  
  39.    multiplication();
  40.    for(;;)
  41.    {
  42.       if( *Lineptr=='+' )
  43.       {
  44.          ++Lineptr;
  45.          multiplication();
  46.          push( pop() + pop() );
  47.       }
  48.       else if ( *Lineptr=='-' )
  49.       {
  50.          ++Lineptr;
  51.          multiplication();
  52.          num = pop();
  53.          push( pop() - num );
  54.       }
  55.       else
  56.          return;
  57.    }
  58. }
  59.  
  60. multiplication()
  61. {
  62.    int num;
  63.  
  64.    number();
  65.    for(;;)
  66.    {
  67.       if( *Lineptr=='*' )
  68.       {
  69.          ++Lineptr;
  70.          number();
  71.          push( pop() * pop() );
  72.       }
  73.       else if ( *Lineptr=='/' )
  74.       {
  75.          ++Lineptr;
  76.          number();
  77.          num = pop();
  78.          push( pop() / num );
  79.       }
  80.       else
  81.          return;
  82.    }
  83. }
  84.  
  85. push( n )
  86. {
  87.    if( Stackptr<Stacktop )
  88.       return Stack[ Stackptr++ ] = n;
  89.    puts( "stack overflow\n" );
  90. }
  91.  
  92. pop()
  93. {
  94.    if( Stackptr>0 )
  95.       return Stack[ --Stackptr ];
  96.    puts( "stack underflow\n" );
  97. }
  98.  
  99. isdigit(c){ return '0'<=c && c<='9';}
  100.