Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1443
  • Last Modified:

Integer calculator in C++

I have to write a program which will perform integer arithmetic operations on integers up to 200 digits in significance.  You need to implement only the +, *, *=,=,<=,+=,<<, and >> operators.  Use the following main():

void main()
{
   BigNum limit(100);
   BigNum(0);
   BigNum fact(1);
   BigNum inc_value(1);
   int j=1;
   for(BigNum i=1; i <= limit; i += inc_value)
   {
       sum = sum + i;
       fact *= i;
   }
   cout << "Sum from 1 to "
        << limit << "=" << sum << endl;
   cout << "Factorial of " << limit
        << "=" << fact << endl;

   BigNum first(0), second(0);
   cout <<"Enter First Number --->";
   cin>> first;
   cout << "Enter Second Number--->";
   cin >> second;

   cout << endl << "The answer is "
         << first << "+" << second
          << "=" << first + second << endl;
   cout <<"The product is " << first * second <<endl;
}

You have only 'til July 7th to get the answer.
Thanks.
0
ash2902
Asked:
ash2902
  • 7
  • 6
  • 4
  • +6
1 Solution
 
ash2902Author Commented:
If you want to send me the source via attachment then please send it to secret_me25@hotmail.com
0
 
tdubroffCommented:
Im not going to write this for you, but the way I would do it would be to create a class something like this:

class long200 {
   private:
   char _long200[400];       // ascii character representation of very long integer (200 * 2 for mult)
   int    _carry;                      // either true or false
   // put any private methods here

   public:
   // put all your operator overloads and public methods here
};


Now, to do addition you've got to do it just like you learned it in elementary school - one number at a time with a carry consideration.  To do this, you take each element of the char array inside the class, convert it to its integer form, add the two numbers, modulo by 10, and set the _carry variable depending on if the result is greater than 10.  Meaning, if the result is greater than 10, the _carry variable equals 1.   Next time, do the same thing and add the _carry flag to the result....etc.

You can use similar methods for the other operators you have to do.  For multiply, you can use the _carry flag as the '10's' multiplier (or whatever).

Hoped this helped you out.
0
 
yonatCommented:
Wat you need is a "big integer" class. These are available in many cryptographic libraries. For pointers, see http://www.cs.hut.fi/crypto/software.html . My personal favorite is crypto++ available from http://www.eskimo.com/~weidai/cryptlib.html .
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.

 
alamoCommented:
Asking others to do your homework assignments for you is not cool.
0
 
rbrCommented:
I can give you a programmm written in C. Send an email to rbr@physik.kfunigraz.ac.at
0
 
nietodCommented:
>> Asking others to do your homework assignments for you is not cool.
Not only is it not cool.  It is accadmically dishonest and grounds for expulsion.
It is also grounds for removal from this site under your customer service agreement.  (Based on the ethics rule.)
0
 
ash2902Author Commented:
Dear friends nietod and alamo,

well this is not a homework and it is for my own good.. i am learning C++ on my own and i am trying to see where i went wrong. i have already written the program but i want to get some other responses and see where i could have improved my work.

Sorry for the misunderstanding, again this is not a homework assignment.
 Thanks.
0
 
nietodCommented:
Then you should post your existing code and let us offer suggestions.  That is the best way to improve.  If your code is too long to post, you could e-mail it to me at nietod@theshop.net.  (or any other expert who offers their e-mail address.)
0
 
StapleheadCommented:
ash:

your first login here was 7/5, on which date you posted this question.  

you said "i *have* *to* write a program", which sounds less like a personal study exercise than an assignment.  

your wording "you need only implement..." sounds like it's right out of a programming assignment, and "use the following main()" sounds like the kind of constraint that an instructor would use to make sure that students implement the right kind of assignment.

You also say "you only have until July 7th"; if this is for your own personal edification, why should a two-day deadline be important to you?

p.s., please tell your instructor that "void main()" is incorrect.  it should be "int main()"...
0
 
tdubroffCommented:
I use void main() all the time....
0
 
ash2902Author Commented:
Hi Staplehead,
well it does seem to be an assignment .. i agree.. but it is out of a book called Deitel & Deitel... i wanted to do it before i go for another job interview in Atlanta.. anyway, i just wanna clarify this.. i am not a student first of all../ I found this site and thought that it was cool.....and thought that i could improve my skills here... there is no deadline for this question i asked...I like to get different source codes from different people...and then see where i can improve my skills...I am going to cut and paste what i have written and see what is wrong with it.  If you can help, that would be great..if not.. too bad.

// The Preprocessor
#include<iostream.h>
#include<conio.h>

/*------------------------------------------------------------------*/

void main(void)    // Starting The Main Program
{
 int a, b;  // Declairing 2 Integer Variables a and b

 char op,              // Character Variable to read in Operator (+,-,*,/)
          AnotherTry; // Character Variable to continue or end program


 a=0;          // Initializing the Value for all variables
 b=0;
 op='\0';
 AnotherTry='\0';

 do     // Begining Do While Loop for Primary Routine
 {
  cout << "\nEnter the First Integer: "; // Enter the first integer
  cin >> a;

  cout << "\nEnter the Second Integer: "; // Enter the second integer
  cin >> b;

  do   // Begining of Do While Loop for Getting the Operator
  {
   cout << "\nEnter the opperation you would like to perform\n";
   cout << "ie. (+,-,*,/): ";
   op=getch();   // Get the operator

/*
  the  getch()  function will get a character from the keyboard
  from a single key press.  You do not have to enter after you press
  the key.  Requires the #include<conio.h> in the preprocessor
*/
//          Check to make sure the right key was pressed
   if( (op != '+') && (op != '-') && (op != '*') && (op != '/') )
   {
    cout << "\nYour pressed \"" << op << "\" please try again" ;
   }
  }while( (op != '+') && (op != '-') && (op != '*') && (op != '/') );
//  End of Do While Loop for Getting the Operator
//  Checks to see if  op is equal to + OR - OR * OR /

  cout << "\n";       //  Return a line

  if(op == '+')        // Adding
  {
   cout << a << " + " << b << " = " << (a+b);
  }
  else if(op == '-')   // Subtracting
  {
   cout << a << " - " << b << " = " << (a-b);
  }
  else if(op == '*')   // Multiplication
  {
   cout << a << " * " << b << " = " << (a*b);
  }
  else if(op == '/')   // Division
  {                    // check for division by zero
   if (b!=0){cout << a << " / " << b << " = " << (a/b);}
   else {cout << "Division by zero is not allowed.\n";}
  }

  cout << "\n\nDo you want to Continue? (y or n): ";
  AnotherTry=getch();

 }while( (AnotherTry=='Y') || (AnotherTry=='y') );   // Checking Loop Condition
//   End of Primary Do While Loop

}  // End of Main Program

0
 
ash2902Author Commented:
I apologize for any misunderstanding to everybody..

thank you
0
 
rbrCommented:
I send you the programm 2 times.
0
 
nietodCommented:
Here is a small improvement.  You do not have to test the validity of the character twice.

while (true)   // Begining of Do While Loop for Getting the Operator
{
        cout << "\nEnter the opperation you would like to perform\n";
        cout << "ie. (+,-,*,/): ";
        op=getch();   // Get the operator

     /*
       the  getch()  function will get a character from the keyboard
       from a single key press.  You do not have to enter after you press
       the key.  Requires the #include<conio.h> in the preprocessor
     */
     //          Check to make sure the right key was pressed
     if( (op == '+') && (op == '-') && (op == '*') && (op == '/') )
           break;

    cout << "\nYour pressed \"" << op << "\" please try again" ;
 }

The next thing to do is to make a and b objects from a class that support the 4 operations.   You could stat out by making them objects that contain a single integer data member and just dot he operations on that member.
0
 
StapleheadCommented:
ash & tdubroff,

void main() will work, but it's not technically correct.  main "should" always return a value, to indicate the success or failure of the program.  (Try posting code to comp.lang.c and see the flames you get!  ;^) )  

I like the Deitel book... wanted to use it in a course i taught, but the other faculty voted it down; they thought the prose was written on too high a level... boo...

anyway, ash, you seem to have come from a Wintel background; my advice to you is to attempt to write the program without the conio functions.  it'd be a good exercise in writing portable code.  Also, as nietod mentions, you need to write a class for your BigNum data type.  the exercise asks you to overload the binary operators, including << and >>.  Once you've done that, you won't need your input loop in main, since you'll be able to write:

BigNum myBigNum1, myBigNum2;
char theOpr;

cin >> myBigNum1 >> theOpr >> myBigNum2;

// a switch here, based on theOpr; i'm only showing one case:
    cout <<  (myBigNum1 + myBigNum2);

etc, etc.

I'd be a little hesitant showing the code you've posted to a prospective employer (i know this wasn't your stated intention, but...); everything you have there, aside from the insertion and extraction operators (on char's, no less!) is C, not C++ ...

Finally, your code doesn't handle the assignment; you *can't* do operations on integral numbers of up to 200 digits.  Hint: Is there a type which *can* handle up to 200 significant digits?  If not, how can you represent this number internally to your class?  (After all, you just care that the user can type something that represents a number to him/her, and that you can do mathematical operations on it...)

good luck; ask more questions as you pursue the C++ implementation of your program!

                      S.
0
 
ash2902Author Commented:
Thanks for all the help guys.. I will be out of town 'til friday and then i will start working on the program.  i really appreciate your help.


0
 
VEngineerCommented:
class BigNum is implemented very well in Cohoon and Davidson's book "C++ Program Design."  It uses dynamic allocation to allow an unlimited (dependent on how much resource your system has) amount of digits.  You can learn quite a bit about C++ with the software projects in that book.  Much better than Deitel and Deitel's book (which does not provide BigNum as an example either).
0
 
StapleheadCommented:
VEngineer,

Funny you should mention the Cohoon text... that's the one that was decided on, in my case!  Still, in ch 2 or 3, he gives an exercise "allow the user to key in an integer number between 12 & 15 digits, and put commas in the appropriate places".  

Try throwing _that_ one at an 18-year old audience, and see how long it takes before they start asking themselves, "what is a '12 digit integer', and what does it mean when i key one in?"  ;^)

I'll agree, though, that the Cohoon is much more approachable by an introductory audience...
0
 
ash2902Author Commented:
I managed to run this program and here is my source code. Any comments??


#include <iostream.h>
#include <ostream.h>
#include <math.h>

class BigNum
{
 private:
  long int number;
  int ten;
  float flt_numb;
  bool too_big;
 public:
  BigNum(int);
  BigNum operator+(BigNum );
  BigNum operator*(BigNum );
  BigNum operator*=(BigNum );
  BigNum operator=(BigNum );
  bool operator<=(BigNum );
  BigNum operator+=(BigNum );
  friend ostream &operator<<(ostream &, BigNum &);
  friend istream &operator>>(istream &, BigNum &);
};


BigNum::BigNum(int n)
{
 if(n <= pow(10,200)-1)
 {
  number = n;
  flt_numb = 1;
  ten = 0;
  too_big = false;
 }
 else
 {
  cout << " Too big number\n";
 }
 return;
}


BigNum BigNum::operator+(BigNum sec_numb)
{
 BigNum sum(0);
 sum.number = number+sec_numb.number;
 return sum;
}


BigNum BigNum::operator*(BigNum sec_numb)
{
 BigNum prod(0);
 prod.number = number*sec_numb.number;
 return prod;
}


BigNum BigNum::operator*=(BigNum next_numb)
{
 number*=next_numb.number;
 if(number >= pow(2,30))
 {
  flt_numb*=number/pow(10,9);
  ten+=9;
  number = 1;
  too_big=true;
 }
 else
 {
  if(next_numb.number==100)
  {
   flt_numb*=number;
  }
 }
 return *this;
}


BigNum BigNum::operator=(BigNum value)
{
 number = value.number;
 return *this;
}


bool BigNum::operator<=(BigNum value)
{
 return (number <= value.number);
}


BigNum BigNum::operator+=(BigNum sec_numb)
{
 number+=sec_numb.number;
 return *this;
}


ostream &operator<<(ostream &out, BigNum &BigNumber)
{
 if(!BigNumber.too_big)
 {
  out << BigNumber.number;
 }
 else
 {
  out << BigNumber.flt_numb << "E" << BigNumber.ten<<endl;
 }
 return out;
}


istream &operator>>(istream &in, BigNum &BigNumber)
{
 in >> BigNumber.number;
 return in;
}

void main()
{
 BigNum limit(100);
 BigNum sum(0);              
 BigNum fact(1);
 BigNum inc_value(1);
 int j=1;
 for(BigNum i=1; i<= 100; i+=inc_value)
 {
  sum = sum+1;
  fact*=i;
 }
 cout << "Sum from 1 to " << limit << " = " << sum << endl;
 cout << "Factorial of " << limit << " = " << fact << endl;

 BigNum first(0), second(0);
 cout << "Enter First Number->";
 cin >> first;
 cout << "Enter Second Number->";
 cin >> second;

 cout << endl << "The answer is" << first << " + " << second
       << " = " << first+second << endl;
 cout << "The Product is " << first*second << endl;
}


0
 
nietodCommented:
Its a good start... but there you still have a ways to go.  The critical program is that you still can't handle numbers with more than 200 digits.  You need a mechanism for storing those digits.

I think the best bet for you would be to use BCD or Binary Coded Decimal to store the digits.  In this technique, givin an number of X digits, you allocate an array of bytes and store one digit in each byte.  The if you were going to store a 1245 in the object, you would allocate an array of 4 bytes and would store a pointer to this array inside the object, then you would place a 1 in the first byte of the array, a 2 in the second byte, a 4 in the third byte and so on.
0
 
nietodCommented:
The class needs to store 2 things to make this work
1.  a pointer to the array of digits.
2.  the length of the array of digits.

I would work on:
Defining the class to use this method
Writing  the constructors for this method
Writing the destructor for this method.

I would commment out the "guts" of you math procedures, but leave the definition of the math procedures for the moment.
0
 
StapleheadCommented:
ash,

just to followup on nietod's comment, keep in mind that he's talking about *implementation*, not *interface*...

if you're implementing a number stored as BCD, you shouldn't force the user of your code to deal exclusively in BCD arrays.  overload your constructor, allowing entry of a numeric string.

in fact, you might consider defining a class which holds a BCD array, since this seems (if you use nietod's suggestion) to be core to an implementation.  once you have the BCD array down, then use it in your BigNumber class as the way you store your data.

of course, an alternate implementation would be with strings...

larry

p.s. to Nietod: umm, i always thought of BCD as a way to store numeric strings at  a half-byte per numeric digit; using one byte per char isn't more efficient than
using 8-byte characters.  wouldn't a string implementation be more straightforward..?!  (it's a monday... maybe my brain hasn't kicked in yet...)
0
 
nietodCommented:
staplehead, BCD is any method for representing a number by storing its seperate digits in a binary form.  As you said, you could store it as a string, that would be ASCII BCD.  If you store each digit in a seperate byte that is Unpacked BCD.  If you store two digits in a byte that is Packed BCD.

In general, unpacked BCD is the easiest to work with, so I suggested that.
0
 
ash2902Author Commented:
thanks guys i will be working on it some more.....it definetely needs some more to be worked on .....
0
 
duneramCommented:
here is another interesting page to consider http://www.geocities.com/CapeCanaveral/Hangar/8802   

Ever hear of Trachtenburg?
0
 
rbrCommented:
Any comments why you reject my anwser!
Don't you get the program?

0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

  • 7
  • 6
  • 4
  • +6
Tackle projects and never again get stuck behind a technical roadblock.
Join Now