## Large numbers subtraction using arrays

Moderators: Darobat, RecursiveS, Dante Shamest, Bugdude, Wizard

### Large numbers subtraction using arrays

Hi all, i have this following program to solve and it took me long time to figure it out.

Write a program which promts the user to enter 2 positive integers, each with up to 50 digits, then subtracts the second number from the first number, and prints the answer. You should use an array to store eaxh of the integers, with one digit in each array element. Each input should be in the normal format, e.g.
enter first integer
15615615484321315161231

enter second integer
78945643554895112

Similarly the output of the answer should be in the normal format, i.e. the format that you expect to get from a calculatormwith a large enough display.

the difference is: 48494556421684

or

the difference is: -4564864545646

The code i tried first is the following but after finishing, i could not make the subtraction..
(i could not initialise the 2 arrays to do the subtraction)

#include<iostream>
using namespace std;

void read_int_as_array ( int input[] , int size, int& numdigits, bool& success);

#endif

//
// parameter input: array to hold the digits of the integer
// parameter size: the size of the array
// parameter numdigits: the number of digits of the integer read in
// parameter success: indicates that integer was read successfully,
// or otherwise.
//
//
// This function reads an integer of up to "size" digits
// and stores the digits in the array "input".
//

void read_int_as_array(int input[], int size, int& numdigits, bool& success)

{
char temp;
int i;
success = true;
if (size < 1) return;

int count = 0;

// initialise array entries to 0

for (i = 0; i < size; i++)
input[i] = 0;

do
// loop through input characters
{
// get character
cin.get(temp);
// if we have not reached end of line or got too many digits
// place digit into array, converted to int
if ((temp != '\n') && (count < size))
input[count] = int(temp) - int('0');
// if the character was not a digit, make success false
if ((!isdigit(temp)) && (temp != '\n'))
success = false;

// increase counter
count ++;
}
while (temp != '\n');

// set numdigits to avoid counting the end of line character
numdigits = count-1;

MAIN ():

#include <iostream>
using namespace std;

int main()
{
const int MAXSIZE = 50;
int num1[MAXSIZE];
bool success;
int numdigits;

cout << "Enter a positive integer:" << endl;

if (success)
cout << "Valid input" << endl;
else
cout << "Invalid input" << endl;

cout << endl << numdigits << " digits entered" << endl << endl;

for (int i = 0; i < MAXSIZE; i++)
cout << "Array entry " << i << ": " << num1[i] << endl;

char junk; cin.get(junk);

return 0;
}

bentouzas25

Posts: 4
Joined: Sun Feb 10, 2013 11:00 am

### Re: Large numbers subtraction using arrays

Please use code tags if you post code in the future.

What have you tried to subtract the numbers? It basically works like you learn subtraction in elementary. Subtract the last cipher of number of number 2 from the last cipher of number 1, store the result and save the carry, Then go to the next cipher and don't forget the carry. And so on until you are done.
You need to know the lenth of both numbers and it is easier if you allways subtract the lower number from the higher one. If the first number is the lower you can swap the numbers and add a "-".
Who needs a signature anyway.

exomo

Posts: 867
Joined: Fri Sep 26, 2003 12:30 pm

### Re: Large numbers subtraction using arrays

My problem is that i cannot implement the code for subtraction, and i dont know how to do it..
Using a loop of some kind??
bentouzas25

Posts: 4
Joined: Sun Feb 10, 2013 11:00 am

### Re: Large numbers subtraction using arrays

Sure you need a loop. Loop through all the digits and do the operations I mentioned above.
Give it a try. If you don't get it working post the code you have tried and I'll look at it.
Who needs a signature anyway.

exomo

Posts: 867
Joined: Fri Sep 26, 2003 12:30 pm

### Re: Large numbers subtraction using arrays

This is the code that i have worked so far..
It really troubles me how to get the carry inside..

Code: Select all
`#ifndef FARRAY_H#define FARRAY_Hlong int const MAXSIZE = 50;      void welcome();   void read(int input[] , int size, int& digits, bool& brief);   void check_entry(int input[] , int size, int& digits, bool& brief);   int subtract(int num1[], int num2[], int size);   void print_sub();#endif`

Farray.cpp :
Code: Select all
`#include "Farray.h"#include <iostream>using namespace std;void welcome(){   cout << "Welcome to the Long Int Subtraction Generator" << endl       << "You can insert two large integers" << endl       << "and subtract them usinng this program." << endl       << "The numbers can be up to 50 Digits." << endl       << "For example: 543350987 - 3245987 = 540105000" << endl       << " Enjoy!!!!" << endl;   }void read(int input[] , int size, int& digits, bool& brief){   char temporary;   int a;   brief = true;   if (size < 1) return;      int counter = 0;      // initialise array entries to 0   for (a = 0; a < size; a++)      input[a] = 0;      do   // loop through input characters   {      // get character      cin.get(temporary);        // if we have not reached end of line or got too many digits      // place digit into array, converted to int      if ((temporary != '\n') && (counter < size))         input[counter] = int(temporary) - int('0');      // if the character was not a digit, make success false      if ((!isdigit(temporary)) && (temporary != '\n'))         brief = false;      // increase counter      counter ++;   }   while (temporary != '\n');   // set numdigits to avoid counting the end of line character   digits = counter-1;   // if there were too many digits, set success to false   if (digits > size)      brief = false;   return;      }void check_entry(int input[], int size, int& digits, bool& brief){   if (brief)      cout << "The value that you entered is VALID." << endl;   else      cout << "The value that you entered is INVALID." << endl          << "Please enter a positive value, and no characters." << endl          << "The number that you will enter must be up to 50 digits." <<endl;   cout << endl  << "The number of digits that you have entered are:  "<< digits << endl << endl;}int subtract(int num1[], int num2[], int size){   int result[] ={0};   int i;   cout << "The result of the subtraction of the two long integers is:  " ;   for ( i = size; i >= 0; i--)   {      if (num1[i] > num2[i])         result[i] = num1[i] - num2[i];      else if (num1[i] < num2[i])         result[i] = num2[i] - num1[i];      else         result[i] = 0;               }      return result[i];}`

main.cpp :
Code: Select all
`#include "Farray.h"#include <iostream>using namespace std;int main(){   int const MAXSIZE = 50;   int pnum1[MAXSIZE], pnum2[MAXSIZE], digits;   bool great;     welcome ();    cout << "Please enter the first positive integer of your choice." << endl;    read(pnum1, MAXSIZE, digits, great);    check_entry(pnum1, MAXSIZE, digits,  great);   cout << "Please enter the second positive integer of our chioce." << endl;   read(pnum2, MAXSIZE, digits, great);   check_entry(pnum2, MAXSIZE, digits,  great);                      cout << "The difference between the two integers you have entered is: "  << endl;       subtract (pnum1, pnum2, MAXSIZE);return 0;}`
bentouzas25

Posts: 4
Joined: Sun Feb 10, 2013 11:00 am

### Re: Large numbers subtraction using arrays

exomo wrote:Sure you need a loop. Loop through all the digits and do the operations I mentioned above.
Give it a try. If you don't get it working post the code you have tried and I'll look at it.

Code: Select all
`#ifndef FARRAY_H#define FARRAY_Hlong int const MAXSIZE = 50;      void welcome();   void read(int input[] , int size, int& digits, bool& brief);   void check_entry(int input[] , int size, int& digits, bool& brief);   int subtract(int num1[], int num2[]);   void print_sub();#endif`

Functions :
Code: Select all
`#include "Farray.h"#include <iostream>using namespace std;void welcome(){   cout << "Welcome to the Long Int Subtraction Generator" << endl       << "You can insert two large integers" << endl       << "and subtract them usinng this program." << endl       << "The numbers can be up to 50 Digits." << endl       << "For example: 543350987 - 3245987 = 540105000" << endl       << " Enjoy!!!!" << endl;   }void read(int input[] , int size, int& digits, bool& brief){   char temporary;   int a;   brief = true;   if (size < 1) return;      int counter = 0;      // initialise array entries to 0   for (a = 0; a < size; a++)      input[a] = 0;      do   // loop through input characters   {      // get character      cin.get(temporary);        // if we have not reached end of line or got too many digits      // place digit into array, converted to int      if ((temporary != '\n') && (counter < size))         input[counter] = int(temporary) - int('0');      // if the character was not a digit, make success false      if ((!isdigit(temporary)) && (temporary != '\n'))         brief = false;      // increase counter      counter ++;   }   while (temporary != '\n');   // set numdigits to avoid counting the end of line character   digits = counter-1;   // if there were too many digits, set success to false   if (digits > size)      brief = false;   return;      }void check_entry(int input[], int size, int& digits, bool& brief){   if (brief)      cout << "The value that you entered is VALID." << endl;   else      cout << "The value that you entered is INVALID." << endl          << "Please enter a positive value, and no characters." << endl          << "The number that you will enter must be up to 50 digits." <<endl;   cout << endl  << "The number of digits that you have entered are:  "<< digits << endl << endl;}int subtract(int num1[], int num2[] ){   int result[] = {0};   int i;   int carry = 0;   cout << "The result of the subtraction of the two long integers is:  " ;   for ( i = MAXSIZE; i >= 0; i--)   {      if (num1[i] > num2[i])      {   result[i] = num1[i] - num2[i] ;               }      else if (num1[i] < num2[i])      {         result[i] = (10+ num1[i]) - num2[i];         num1[i-1]= num1[i-1] - 1;      }      else         result[i] = 0;                              }      return result[i];   }`

Main :
Code: Select all
`#include "Farray.h"#include <iostream>using namespace std;int main(){   int const MAXSIZE = 50;   int pnum1[MAXSIZE], pnum2[MAXSIZE], digits1, digits2;   int save_array[MAXSIZE];   int diff;   bool great;     welcome ();    cout << "Please enter the first positive integer of your choice." << endl;    read(pnum1, MAXSIZE, digits1, great);    check_entry(pnum1, MAXSIZE, digits1,  great);   cout << "Please enter the second positive integer of our chioce." << endl;   read(pnum2, MAXSIZE, digits2, great);   check_entry(pnum2, MAXSIZE, digits2,  great);   diff = digits1-digits2;   if (diff=0)   {   }   else if (diff > 0)   {      for ( int i =0 ; i == diff; i++)      {         save_array[i] = 0;      }      for (int i=0;i=digits2; i++)      {         save_array[i +diff] = pnum2[i];                }   }   else   {      for ( int i = 0; i == diff; i++)      {         save_array[i] = 0;      }      for (int i = 0; i == digits1; i++)      {         save_array[i +diff] = pnum1[i];      }   }               subtract(pnum1, pnum2);             return 0;}`

I updated the code inserting in the main a statement to put zeros(0) in front of the numbers if they are not equal in digits...
bentouzas25

Posts: 4
Joined: Sun Feb 10, 2013 11:00 am

### Re: Large numbers subtraction using arrays

Code: Select all
`if (diff=0)`
You want to use ==
Code: Select all
`for ( int i =0 ; i == diff; i++)`
This loop doesn't run very often. If diff is 0 the loop will run once.
Code: Select all
`for (int i=0; i=digits2; i++)`
missing = again.

I guess what you want to do is something like the following:
Code: Select all
`for ( int i =0 ; i < diff; i++)        {            save_array[i] = '0';        }        for (int i=0; i<digits2; i++)        {            save_array[i +diff] = pnum2[i];        }`

You still have to call the subtract function with the "new" array. And if the numbers have the same length you still want to know which one is higher.

Code: Select all
`for ( i = MAXSIZE; i >= 0; i--)`

index MAXSIZE is out of array bounds, highest valid index is MAXSIZE-1, but this is still not valid because you don't have valid characters in all the array fields. You have to pass the size of the numbers (if you pass the "equalized" arrays).
Who needs a signature anyway.

exomo

Posts: 867
Joined: Fri Sep 26, 2003 12:30 pm

### Re: Large numbers subtraction using arrays

Have you tried using a loop? Commercial Real Estate Cincinnati
richlong217

Posts: 9
Joined: Mon Feb 01, 2021 3:47 am

### Re: Large numbers subtraction using arrays

Maybe you can try using a loop of some kind? Please let me know if you resolved this issue.