I have an assignment wherein I am supposed to use dynamic arrays to store two integers of any size and add those two integers together. The goal of this assignment is to be able to add together two numbers that you normally could not add together due to length. This is what I have so far. I thought this would work, but I seem to be having trouble carrying over a digit when the two added values are greater than 9. I have included the assignment verbatim below the code segment if I didn't explain the problem well enough.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
|
#include <iostream>
using namespace std;
int main()
{
cout << "Please enter the length of your number: ";
int y;
cin >> y;
cout << "Please enter your first number: ";
int x;
cin >> x;
cout << "Please enter your second number: ";
int q;
cin >> q;
int *p;
p = new int[y];
for (int i = 0; i < y; i++) {
p[i] = x % 10;
x = x / 10;
}
int *j;
j = new int[y];
for (int i = 0; i < y; i++) {
j[i] = q % 10;
q = q / 10;
}
for (int i = y - 1; i != -1; i--) {
cout << (j[i] + p[i]) % 10;
if ((j[i] + p[i]) % 10 != j[i] + p[i])
j[i - 1] = j[i - 1] + 1;
}
}
|
C++ Programming Assignment 7.1
CSC 10
1 Large Integer Arithmetic (10 points)
A dynamic array can be used to store large integers one digit at a time. For
example, the integer 1234 could be store in the array a by setting a[0] to 1,
a[1] to 2, a[2] to 3, and a[3] to 4. However, for this project you might nd
it useful to store the digits backward.
You are to write a program that reads in one integer rst indicating the
digits in length the user would like to work with for integers addition, then
reads in two positive integers (of digits at most in length)and then outputs
the sum of the two numbers. Include a loop that allows the user to continue
to do more additions until the user says the program should end