I'm relatively new to programming :).
Suppose I wanted to create a program which prompts a user to enter two positive numbers up to 50 digits long, which then subtracts the second number from the first number.
For example:
The user enters the first positive number: 239834095803945862440385983452184985298358
second number: 939542309853120721934217021372984729812
===========================================================================
Program outputs the difference: 238894553494092741718901766430812000568564
OR, if negative: -29837430045
===========================================================================
Each digit of the numbers will be stored as individual elements in an array. Here is how I am currently taking in the user input:
int read_array(int int_array[], int MAX_SIZE) {
char number;
int count = 0;
//set all array entries to 0.
for (int i = 0; i < MAX_SIZE; i++){
int_array[i] = 0;
}
do { //processes each individual char in the istream
cin.get(number);
// puts char on to the array until it hits the
// end of the number (end of the line)
if(( number != '\n') && (count < MAX_SIZE) && (isdigit(number))) {
int_array[count] = int(number) - int('0');
}
count++; //increments count
} while (number != '\n');
//tests if number is too large
int digitcount = count - 1;
if (digitcount > MAX_SIZE) {
cout << endl << "ERROR: The number is above 50 digits!" << endl;
return 0;
}
THE PROBLEM:
HOW to do the subtraction is eluding me.I have been trying to solve this problem for two weeks and it's most likely something trivial I have missed.
I have tried:
- Converting array of elements back into one whole int
- Writing my own program to do long subtraction on the numbers
etc...
However, the output is ONLY successful up until a certain number of digits and/or if they're positive/negative numbers. I'm stumped and I'm not sure what the best way is to subtract two positive number arrays to get a successful output that can accommodate for positive and negative numbers as shown in the example. ANY HELP GREATLY APPRECIATED :).
EDIT: my attempts:
#include "long_sub.h"
#include <sstream>
#include <vector>
using namespace std;
int long_sub(int a[], int b[], const int size) {
stringstream ss;
int const sizes = 50;
int c = 0; //borrow number
int borrow = 1; // the '1' that gets carried to the borrowed number
int r[sizes];
for (int i = 0; i < size; i++) {
r[i] = 0;
}
//initialise answer array to 0.
for (int i = size - 1; i >= 0; i--) {
//handles zeros
if (a[i] < b[i] && a[i]) {
//takes the borrow from the next unit and appends to a.
ss << borrow << a[i];
ss >> c;
ss.clear(); // clears stringstream for next potential borrow.
int temp = c - b[i];
r[i] = abs(temp);
} else {
int temp = a[i] - b[i];
r[i] = abs(temp);
}
}
for (int i = 0; i <= size - 1; i++ ) {
cout << r[i];
}
cout << endl;
return r[sizes];
}