0

Hello

I have a task to perform an addition of 2 Big Integers. Each Big Integer is stored in a linked list in reversed order. **Is my add function correct?**

For eg;

we have 2 Big Ints to add together

First BigInt = 245 { strored in the linked list as 5 - 4 - 2 }

2nd BigInt = 23 { strored in the linked list as 3 - 2 }

```
bigInt bigInt::add(bigInt J)
{
// Write this function correctly.
// You could simply insert an appropriate loop
// where indicated below.
int i, j, k, s;
int carry = 0;
node * currentp = firstp;
node * currentJp = J.firstp;
node * result;
makeEmpty(result);
// Insert an appropriate loop here.
// Build up result using comp.
while (currentp != NULL) {
i = currentp->data + currentJp->data + carry;
if (i>=10) {
carry = 1;
i = i%10;
}
else carry = 0;
result = comp(result,i);
currentp = currentp->next;
currentJp = currentJp->next;
}
invert(result); // result needs to be inverted to obtain correct order of digits.
bigInt K(result);
return K;
}
```

Whole source code:

```
#include "bigInt.h"
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
// Definition of node
struct node
{
int data;
node * next;
};
/* Member functions of the class bigInt
node * comp(node * L, int x); // returns composition of L and x
// (i.e. the list obtained by inserting a new node containing x
// at the head of L)
class bigInt
{
public:
bigInt add(bigInt J);
private:
node * firstp;
};
*/
bigInt bigInt::add(bigInt J)
{
// Write this function correctly.
// You could simply insert an appropriate loop
// where indicated below.
int i, j, k, s;
int carry = 0;
node * currentp = firstp;
node * currentJp = J.firstp;
node * result;
makeEmpty(result);
// Insert an appropriate loop here.
// Build up result using comp.
while (currentp != NULL) {
i = currentp->data + currentJp->data + carry;
if (i>=10) {
carry = 1;
i = i%10;
}
else carry = 0;
result = comp(result,i);
currentp = currentp->next;
currentJp = currentJp->next;
}
invert(result); // result needs to be inverted to obtain correct order of digits.
bigInt K(result);
return K;
}
node * comp(node * L, int x)
{
node *newp = new node;
newp->data = x;
newp->next = L;
return newp;
}
```

My lecturer gave us half of the function 'add' already done but I haven't used all of the variables in the template. Why did they give us so many variables??

Template given by lecturer:

```
bigInt bigInt::add(bigInt J)
{
// Write this function correctly.
// You could simply insert an appropriate loop
// where indicated below.
int i, j, k, s;
int carry = 0;
node * currentp = firstp;
node * currentJp = J.firstp;
node * result;
makeEmpty(result);
// Insert an appropriate loop here.
// Build up result using comp.
invert(result); // result needs to be inverted to obtain correct order of digits.
bigInt K(result);
return K;
}
```