Solved

# Simple C Calculator

Posted on 1998-04-24
471 Views
I would like the sourcecode (c language and cobol) for a simple calculator which does addition, subtraction, multiplication and division.
0
Question by:lovindere

LVL 16

Expert Comment

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

Author Comment

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

LVL 2

Expert Comment

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

LVL 4

Expert Comment

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

Author Comment

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

LVL 16

Accepted Solution

I will be happy to accept a grade. Now that I have answered it,
you should see the opportunity to grade appear.

Thanx.

0

Author Comment

tx imladris. forgive a desperate novice:-)
0

LVL 16

Expert Comment

No worries. Anytime.

0

## Featured Post

Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
The goal of this video is to provide viewers with basic examples to understand recursion in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.