L-7 MCS 275 Wed 24 Jan 2001

Below is the listing for the program we discussed in class.
/* L-7 MCS 275 primitive calculator to illustrate arguments to main */

#include <stdio.h>

int number (char s[]);
/* returns the number in the string s,
   e.g.: returns 123 when s = "123" */

int main(int argc, char *argv[])
/* argc = number of arguments to the program,
   argv = array of strings of size argc:
     argv[0] = name of the program;
     argv[1] = string containing the first argument;
     argv[argc-1] = string with the last argument. */
{
   int op,n1,n2,result;

   if (argc > 3)
   {
      n1 = number(argv[1]);
      n2 = number(argv[3]);
      op = argv[2][0];
      switch (op)
      {
         case '+' : result = n1+n2; break;
         case '-' : result = n1-n2; break;
         case 'x' : result = n1*n2; break;
         case ':' : result = n1/n2; break;
         default : printf("Operation not supported.\n");
      }
      printf("%d %s %d = %d\n", n1, argv[2], n2, result);
   }
   return 0;
}

int number (char s[])
{
   int nb = s[0] - '0';
   int i;

   for (i = 1; s[i] != '\0'; i++) 
      nb = nb*10 + (s[i] - '0');
   return nb;
}