Can't seem to understand this array.

I need to create a function call convertToDecimal. This will then take an int array { 3, 2, 4 } and a length of the array, and will return a single integer where each part of the array is a digit in the new integer (324). To do this I would need to multiply:
3*10^2 +
2*10^1 +
4*10^0 = 324

I got the code to work but I would like to do it like the example above.
This is the code I have with the array { 1, 2, 3, 4, 5 }:

int sum2 = 0;

void convertToDecimal(int my_array[], int i)
{
for (int i = 0; i < 5; i++)
{
int num = my_array[i];
if (num != 0) {
while (num > 0) {
sum2 *= 10;
num /= 10;
}
sum2 += my_array[i];
}
else {
sum2 *= 10;
}
}

cout << "The numbers in the array together are " << sum2 << endl;
}

int main()
{
int my_array[] = { 1, 2, 3, 4, 5 };

convertToDecimal(my_array, 5);

system("Pause");
return 0;
}
Last edited on
Just a hint
1
2
3
for(int i=0;i<5:i++){
    num=pow(10,(i-1))
}


Now you get
10000
1000
100
10
1
Oh, I see how to do it now. Thanks a lot!
Just a hint
1
2
3
for(int i=0;i<5:i++){
    num=pow(10,(i-1))
}



Now you get
10000
1000
100
10
1
pow returns a double so the results are not guaranteed.

Since they are integers I would do something like

1
2
3
4
5
6
7
8
9
int const base = 10;
int multiplier = 1;

int result = 0;
for(std::size_t i = arraySize - 1; i > -1; --i)
{
    result += array[i] * multiplier;
    multiplier *= base;
}
Last edited on
Topic archived. No new replies allowed.