XLD_a XLD_a - 2 months ago 9
C++ Question

How to display an array dynamically

I need to create a function that displays the following:

if number is between 0 - 5 then display values 1, 2, 3, 4, 5
if number is between 5 - 10 then display values 2, 4, 6, 8, 10
if number is between 10 - 50 then display values 10, 20, 30, 40, 50
if number is between 50 - 100 then display values 20, 40, 60, 80, 100
if number is between 100 - 500 then display values 100, 200, 300, 400, 500
if number is between 500 - 1000 then display values 200, 400, 600, 800, 1000
if number is between 1000 - 5000 then display values 1000, 2000, 3000, 4000, 5000


and so on...

I'm thinking of working with 2 arrays and then multiply with 10.

int *MyFunct(int number) {

int a[5] = { 1, 2, 3, 4, 5 };
int b[5] = { 2, 4, 6, 8, 10 };


if (number >= 0 && number <= 5) {
return a;
}
else if (number > 5 && number <= 10) {
return b;
}
else if (number > 10 && number <= 50) {
a[1] *= 10;
a[2] *= 10;
a[3] *= 10;
a[4] *= 10;
a[5] *= 10;
}
.
.
.
}


Is there any possibility to do this dynamically or simpler?

Answer

You must first note that you cannot return an automatic array. For this use case, the simplest is to just use static ones.

Then your algorithm can be reworded as:

  • start with the array [1, 2, 3, 4, 5]
  • if the number is less than the last number of the array, return the array
  • else multiply the array alternatively by 2 and 5

In C++ it gives:

int *MyFunc(int n) {
    static const int init[] = {1, 2, 3, 4, 5};  // the initial array
    static int result[5];
    int& max = result[4];  // alias for the last value

    // copy init to result:
    for (int i=0; i<5; i++) result[i] = init[i];

    // find the range of n
    for (;;) {
        if (n <= max) {
            break;
        }
        // multiply alternatively by 2 and by 5
        for (int i=0; i<5; i++) result[i] *= 2; 
        if (n <= max) {
            break;
        }
        for (int i=0; i<5; i++) result[i] *= 5;
    }
    return result;
}

Simple and compact...