?
Solved

Simple C Calculator

Posted on 1998-04-24
8
Medium Priority
?
488 Views
Last Modified: 2010-04-15
I would like the sourcecode (c language and cobol) for a simple calculator which does addition, subtraction, multiplication and division.
0
Comment
Question by:lovindere
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
8 Comments
 
LVL 16

Expert Comment

by:imladris
ID: 1255297
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

by:lovindere
ID: 1255298
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

by:jaked
ID: 1255299
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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 4

Expert Comment

by:jos010697
ID: 1255300
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

by:lovindere
ID: 1255301
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

by:
imladris earned 240 total points
ID: 1255302
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

by:lovindere
ID: 1255303
tx imladris. forgive a desperate novice:-)
0
 
LVL 16

Expert Comment

by:imladris
ID: 1255304
No worries. Anytime.

0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

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…
Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
The goal of this video is to provide viewers with basic examples to understand and use structures in the C programming language.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use nested-loops in the C programming language.
Suggested Courses
Course of the Month9 days, 22 hours left to enroll

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question