I am writing a program for a c++ class that will take in an integer value. display the most significant digit, least significant digit, smallest digit, largest digit, and display the sum of all the digits.
so far, I am trying to cin the integer to iVal then use the % and division to get each digit stored to its own variable for a number below 1,000,000,000. the max integer size on my console is 999,999,999. although, I would like not to set an upper limit for the value this way, but this is what I have so far.
should I be doing this in a different way? I not sure how I can complete all these operations if I don't follow this method.
32 bit integers won't hold more than 10 digits in them, no matter what you do. The best way would be to use an array? Then you would just arr[i] = iVal%10 and iVal = iVal/10 in a loop. Are you familiar with those?
/ Print out least significant digit & most significant digit
void printLeastMostSignificantDigit(int a_integer) {
int tempInteger = a_integer, count = 0;
// Determine the number of digits of the integer
do {
tempInteger = tempInteger / 10;
count++;
} while (tempInteger != 0);
// Set the digits to positive if the integer is negative
if(a_integer < 0)
a_integer = -a_integer;
// Dynamically allocating array to store all the digits
int* digit = newint[count];
// Find the remainder, then move 1 place to the left
for(int index = count - 1; index >= 0; index--) {
digit[index] = a_integer % 10;
a_integer = a_integer / 10;
}
// -1 because array start @ 0, ortherwise out of bound
cout << "The least significant digit: " << digit[count - 1] << endl;
cout << "The most significant digit: " << setw(2) << digit[0] << endl << endl;
displaySmallestLargestSumDigits(digit, count);
delete [] digit;
digit = 0;
return;
}