• C

Simple C Calculator

I would like the sourcecode (c language and cobol) for a simple calculator which does addition, subtraction, multiplication and division.
lovindereAsked:
Who is Participating?
 
imladrisConnect With a Mentor Commented:
I will be happy to accept a grade. Now that I have answered it,
you should see the opportunity to grade appear.

Thanx.

0
 
imladrisCommented:
I don't think you will get much Cobol code in the C Language topic area. But here is a C version. It is commandline and stack oriented. That is to say it works like HP Calculators used to (and maybe still do, I haven't looked at one in ages): enter a number, enter a number, specify an operation. This code even has hex mode and a memory!

#include "stdio.h"

#define Err(n)       printf(errm[n-1])
#define Guard(n)     if(sp<n-1){ Err(1); break; }

char errm[3][40] = { "Insufficient stack elements\n",
                     "Stack full\n",
                     "Invalid input\n"
                   };

char base = 'd',buf[160];
int cp=0;

main()

{       long stk[10],mem,sp;
        int i;
        char c,num[20];

        sp=-1;
        mem=0;

        do
        {       c=getnext();
                switch(c)
                {       case 'x':
                                base='x';
                                if(sp>=0)
                                {       printf("\n");
                                        show(stk[sp]);
                                }
                                break;
                        case 'd':
                                base='d';
                                if(sp>=0)
                                {       printf("\n");
                                        show(stk[sp]);
                                }
                                break;
                        case '+':
                                Guard(2);
                                stk[sp-1]+=stk[sp];
                                --sp;
                                printf("\n");
                                show(stk[sp]);
                                break;
                        case '-':
                                Guard(2);
                                stk[sp-1]-=stk[sp];
                                --sp;
                                printf("\n");
                                show(stk[sp]);
                                break;
                        case '*':
                                Guard(2);
                                stk[sp-1]*=stk[sp];
                                --sp;
                                printf("\n");
                                show(stk[sp]);
                                break;
                        case '/':
                                Guard(2);
                                stk[sp-1]/=stk[sp];
                                --sp;
                                printf("\n");
                                show(stk[sp]);
                                break;
                        case 't':
                                printf("\n");
                                if(sp>=0)show(stk[sp]);
                                break;
                        case 'a':
                                printf("\n");
                                for(i=sp; i>=0; --i)show(stk[i]);
                                break;
                        case 'p':
                                Guard(1);
                                --sp;
                                break;
                        case 's':
                                mem=stk[sp];
                                break;
                        case 'r':
                                stk[sp]=mem;
                                break;
                        case 'm':
                                printf("\n");
                                show(mem);
                                break;
                        case 'q':
                        case '\n':
                        case '\r':
                        case ' ':
                                break;
                        default:
                                if('0'<=c && c<='9')
                                {       if(sp<9)
                                        {       backup();
                                                getnum(num);
                                                ++sp;
                                                if(base=='d')sscanf(num,"%ld",stk+sp);
                                                else sscanf(num,"%lx",stk+sp);
                                        }
                                        else Err(2);
                                }
                                else Err(3);
                }
        } while(c!='q');
}


show(a)
long a;

{       if(base=='d')printf("%ld\n",a);
        else printf("%lx\n",a);
        return;
}

getnext()

{       if(buf[cp]=='\0')getline();
        return(buf[cp++]);
}


backup()

{       if(cp>0)--cp;
        return;
}


getnum(num)
char *num;

{       int dp;

        dp=0;
        while( ('0'<=buf[cp] && buf[cp]<='9') || (base=='x' && 'a'<=buf[cp] && buf[cp]<='f') )num[dp++]=buf[cp++];
        num[dp]='\0';
        return;
}


getline()

{       char *sp,*dp;

        scanf("%s",buf);
        dp=buf;
        for(sp=buf; *sp!='\0'; ++sp)
        {       if(*sp!=8)*dp++=*sp;
                else dp=dp>buf?dp-1:dp;
        }
        *dp='\0';
        cp=0;
        return;
}

0
 
lovindereAuthor Commented:
i need to compile in a unix os.  the answer i was given contains (it appears a lot of syntax errors).  when i try to compile it gives me the error: Object file format error in (filename): read_cur_obj_info: bad file magic number (0x2a2f).  I have created my own calculator as shown below:/* Simple four-function calculator program
 * created by me
  * 04/27/98
*/

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

char Token;

int exp(void);
int term(void);
int factor(void);

void GetToken(void)
{ while (((Token = getchar()) == ' ')
           || (Token == '\t'));
}

void Error(void)
{ printf("Error!\n");
  exit(0);
}

int number(void)
{ if isdigit(Token)
  { int temp = 0;
    while (isdigit(Token))
    { temp = 10*temp + Token - '0';
      Token = getchar();
    }
    /* Don't call GetToken here, since non-digits should
       end a number */
    if ((Token == ' ') || (Token == '\t')) GetToken();
    /* Make sure Token is non-white-space */
    return temp;
  }
  else Error();
  return 0;
}

int factor(void)
{ if (Token == '(')
  { int temp;
    GetToken();
    temp = exp();
    if (Token == ')') GetToken();
    else Error();
    return temp;
  }
  else return number();
}

int term(void)
{ int temp = factor();
  while ((Token == '*')||(Token =='/'))
  { if (Token=='*')
    { GetToken();
      temp *= factor();
    }
    else
    { GetToken();
      temp /= factor();
    }
  }
  return temp;
}

int exp(void)
{ int temp = term();
  while ((Token == '+')||(Token=='-'))
  { if (Token=='+')
    { GetToken();
      temp += term();
    }
    else
    { GetToken();
      temp -= term();
    }
  }
  return temp;
}

int parse(void)
{ printf("Enter an integer arithmetic expression:\n");
  GetToken();
  return exp();
}

main()
{ int result = parse();
  /* insist on seeing end of line to eliminate widows */
  if (Token == '\n')
    printf("value is: %d\n",result);
  else Error();
  return 0;
}

can anyone help.  desperate!  after this i will need to create a checkbook balancer. i haven't even started yet.  new to c language please answer hopefully today!!!
0
The Firewall Audit Checklist

Preparing for a firewall audit today is almost impossible.
AlgoSec, together with some of the largest global organizations and auditors, has created a checklist to follow when preparing for your firewall audit. Simplify risk mitigation while staying compliant all of the time!

 
jakedCommented:
Hmm... I'm guessing that if you don't know how to use the compiler you didn't write the code above... The errors you're getting aren't syntax errors--the code compiles and runs fine. I'm guessing that you have the wrong extender on the file or are somehow invoking the compiler wrong. Try saving the code into a file called 'calc.c' and compiling it with 'cc -o calc calc.c'. Then run the result by typing './calc'.

I think imladris deserves credit because he did post a working calculator program (although his parses postfix expressions instead of infix, which probably isn't what you were looking for, but that's your just desserts for expecting the net to do your homework).

There is a great section about parsing and calculators in The Unix Programming Environment by Kernighan and Pike. You should go check it out. If you're having trouble with C you should also pick up The C Programming Language by Kernighan and Ritchie.
0
 
jos010697Commented:
Just some hackery comment: the 'bad magic number' 0x2a2f happens to be the
ASCII codes for a '/' and a '*' in reversed order; I smell a little endian machine
here, some initial comment line in the source code and some fiddle-diddling with
permission bits. All together this confuses the OS so much that it thinks it's
dealing with an executable file here ...

kind regards,

Jos aka jos@and.nl
0
 
lovindereAuthor Commented:
would like to grade imaldris' answer, but don't know how. first time user, not familiar w/processes. tx for your answer.  for jaked, you're not completely correct, but constructive criticism hasn't hurt me yet. tx for your suggestions.
0
 
lovindereAuthor Commented:
tx imladris. forgive a desperate novice:-)
0
 
imladrisCommented:
No worries. Anytime.

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.