-1

I have been thinking on how to do this for some few hours now.

For example, let's give an array of indefinite length Arr[] = {1,2,3,4} .

(indefinite because it could have any other number of elements)

As it might be obvious, the best way to do this mathematically would probably be multiplying the first element * 1000, + second element * 100, + third element * 10, + fourth element.

So this way the result would be: 1000 + 200 + 30 + 4 = 1234.

The theory is pretty simple, but how can you implement this on a 'for' loop, with the fact that it could have any other number of elements, for example let's suppose it could have 7 elements and the operation would now need a "Seventh element * 100000"? I've been thinking on this for a while and I can't think of a way to write this on a 'for' that makes this possible on the same loop. Do you guys have a suggestion to how could I maybe do this?

Thanks!

Bandit
  • 1

3 Answers3

5

Assuming all your integers are just one digit in base 10:

int result = 0;
for (int i = 0; i < len; ++i) {
    result = result*10 + arr[i];
}
DeducibleSteak
  • 1,286
  • 9
  • 20
1

To let the compiler figure out the array size for you:

template <typename T, size_t size>
int compute(T (&arr)[size]) {
  int result = 0;
  for (size_t i = 0; i < size; i++) {
    result = result * 10 + arr[i];
  }
  return result;
}

Try it online!

Zheng Qu
  • 587
  • 5
  • 17
  • 1
    Also worth noting: C++17 added a function template to get the extent of an array: `template constexpr std::size_t size(const T (&array)[N]) noexcept;` – Ted Lyngmo Feb 10 '20 at 19:50
0
int size = sizeof(Arr) / sizeof(*Arr), p = 1, number = 0;

for(int i = size - 1; i >= 0; i--)
{
    number = number + a[i] * p;
    p *= 10;
}
cout << number;

I think you could try this. The size variable contains a formula to determine the size of the array, the rest is just simple math. I'm going backwards with the for loop, because this is the way my formula works. Hope it helped!

Robert Feduș
  • 274
  • 2
  • 13
  • Two notes about `int size = sizeof(Arr) / sizeof(*Arr)`: Due to [arrays decaying into pointers](https://stackoverflow.com/questions/1461432/what-is-array-decaying) this does not work if you pass the array into a function and in modern C++ you can take advantage of [`std::size`](https://en.cppreference.com/w/cpp/iterator/size). – user4581301 Feb 10 '20 at 19:10
  • Good to know! @user4581301 – Robert Feduș Feb 10 '20 at 19:12