I need to change an integer and put it into an array but in a way that it is read correctly.
Arrays are typically drawn to be read left to right with the 0
element on the left and the largest on the right. However, arrays
are a completely made up concept and are not physical in nature. So
you can draw them and think about them anyway you want. For this
problem having the right side as the 0 element and the left side as
the largest makes much more sense.
Take the example of the number 299,793. We show how it is stored in
the array below. The 3 is in the one's position, the 9 in the 10's
position and so on. This neatly corresponds to the index of the
array. The addition and multiple algorithms given below use this
representation.
bigint
Index: | n | ... | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
Place: | 10^n's | ... | 10^7's | 10^6's | 10^5's | 10000's | 1000's | 100's | 10's | 1's |
Value: | 0 | ... | 0 | 0 | 2 | 9 | 9 | 7 | 9 | 3 |
now i have a constructor bigint::bigint(int); and I know i need to peel off each digit from the int and place it into the appropriate location in the array of int. To do this you need to use integer division and mod.
int digit, num = 128; digit = num % 10; // num mod 10 is 8 in this case. num = num / 10; // num div 10 is 12. digit = num % 10; // digit is now 2 num = num /10; // num is now 1 digit = num % 10; // digit is now 1 num = num /10; // num is now 0
So you can build a loop that goes until num == 0 and peel off each digit, putting them in the array.
my question is how would i build this loop to place them correctly in the array?
CODE IN C++:
#include <iostream>
using namespace std;
int digitCount(int number){
int count = 0 ;
while(number!=0){
number = number / 10 ;
count +=1 ;
}
return count;
}
int main()
{
int number;
cout<<"Enter an integer:";
cin>>number;
int count = digitCount(number);
int arr[count];
int i;
int temp = number;
for(i=count-1;i>=0;i--){
arr[i] = temp%10;
temp = temp / 10;
}
cout<<"Below is your number in the array
form:"<<endl;
for(i=0;i<count;i++)
cout<<arr[i]<<" ";
return 0;
}
OUTPUT:
Get Answers For Free
Most questions answered within 1 hours.