Hey i have a code where i want to add/subtracrt 2 big integer. But i don't know how to do the carry thing.
Does anybody has an idea?
Here is my Code:
#include <iostream.h>
#include <string.h>
#define SIZE 40
class Huge
{
public:
Huge();
void menu();
void rules();
void intadd();
void intsub();
void input();
void output();
int getint(char);
private:
char x[SIZE];
char y[SIZE];
char newX[SIZE];
char newY[SIZE];
char val[SIZE];
};
Huge::Huge()
{
for(int i = 0; i < SIZE; i++)
{
x[i] = '0';
y[i] = '0';
val[i]='0';
}
x[SIZE] = y[SIZE] = '\0';
}
void Huge:: menu()
{
int Choice;
while(Choice != 2)
{
cout<<endl;
cout<<" Press 0 for adding two numbers. "<<endl;
cout<<endl;
cout<<" Press 1 for subtracting two numbers. "<<endl;
cout<<endl;
cout<<" Press 2 for exit the Program. "<<endl;
cin>>Choice;
switch (Choice)
{
case 0:
rules();
intadd();
break;
case 1:
rules();
intsub();
break;
}
}
}
int Huge::getint(char a)
{
return((int)a-48);
}
void Huge:: input()
{
cout<<endl;
cout<<" Enter Your first array. "<<endl;
cout<<endl;
cin>>x;
cout<<" Enter Your second array. "<<endl;
cout<<endl;
cin>>y;
}
void Huge:: rules()
{
cout<<" Put an huge integer in but it has to be under 40 didgits."<<endl;
cout<<endl;
}
void Huge::intadd()
{
int a,b;
int c;
int s,w;
int d=0;
input();
s=strlen(x);
w=strlen(y);
int i;
for(i=s-1;i>=0;i--)
{
newX[d]=x[i];
d++;
}
newX[s] = '\0';
d=0;
for (i=w-1;i>=0;i--)
{
newY[d]=y[i];
d++;
}
newY[w] = '\0';
for(i=0;i<strlen(newX);i++)
{
a=getint(newX[i]);
b=getint(newY[i]);
c=a+b;
val[i]=c+48;
}
for(i=s-1;i>=0;i--)
cout<<val[i];
cout<<endl;
}
void Huge::intsub()
{
int a,b;
int c;
int s,w;
int d=0;
input();
s=strlen(x);
w=strlen(y);
int i;
for(i=s-1;i>=0;i--)
{
newX[d]=x[i];
d++;
}
newX[s] = '\0';
d=0;
for (i=w-1;i>=0;i--)
{
newY[d]=y[i];
d++;
}
newY[w] = '\0';
for(i=0;i<strlen(newX);i++)
{
a=getint(newX[i]);
b=getint(newY[i]);
c=a-b;
val[i]=c+48;
}
for(i=s-1;i>=0;i--)
cout<<val[i];
cout<<endl;
}
int main()
{
Huge h;
h.menu();
return 0;
}