My programming assignment is to perform addition and subtraction operations with large integers up to 20 digits in length by using arrays. The instructions tell us to perform the arithmetic operations when digits are stored starting from the end of the array. For example:
string value1 = "";
cin >> value1; //input 1234
test[19] = 4;
test[18] = 3;
test[17] = 2;
test[16] = 1;
so it'll be easier to perform sum and difference operations. Any unused digits should be initialized to 0.
I started off by writing a for loop to read the last index of the test[] array to the first index. The variable, numDigits, keeps track of all the nonzero values in the array.
include<iostream>
include<string>
using namespace std;
int main()
{
string value1 = "";
int numDigits = 0;
const int Max_Digits = 20;
int test[Max_Digits] = {0};
test[19] = 10;
//cin >> value1;
for (int i = Max_Digits - 1; i >= 0; i--)
{
if (test[i] != 0)
numDigits++;
}
cout << "There are " << numDigits << " nonzero values."; //numDigits == 1
/*cout << "Your number is: " << test[];*/
return 0;
}
So if the user enters "1234" into the string variable, value1, I would want the program to convert the string into an array of digits and output it like 1234 (no commas or spaces) before I continue the assignment.
I wasn't sure whether you needed backwards insertion or forward, so the following demo does both. Pick your choice.
The idea is simple. For backwards insertion you need to create an iterator
i
which is initialized toMax_Digits-1
and decrements as the iterator that goes through the string increments. For forward insertion, you need to get the length of the string usingstd::string::length()
and assign the value withMax_Digits-(strLen-i)
. Thestd::string::length()
function will recalculate the length of the string every time which is called. It unnecessary to pay for that cost, so might as well store it in a variable.For the input:
The result is:
Example: https://rextester.com/MDTL51590
ps. if you don't know what the
constexpr
is, then in this case, simply consider it as a beefed upconst
.