Home > Software engineering >  How do I solve this array problem in C language?
How do I solve this array problem in C language?

Time:10-26

I have 2 arrays: int element[3] = {0, 1, 2}; int quantity[3] = {2, 3, 4}; Now I want a result array that will have two zeros, three ones and four twos. int result[2 3 4] = {0, 0, 1, 1, 1, 2, 2, 2, 2}; How do I do this using loop?

CodePudding user response:

You need to count the number of elements in the result array and to declare either a variable length array with the calculated value or to allocate dynamically such an array.

For example

int quantity[3] = {2, 3, 4};

size_t n = 0;
for ( size_t i = 0; i < 3; i   )
{
    n  = quantity[i];
}

int result[n];

// or
// int *result = malloc( n * sizeof( int ) );

And then in nested loops you need fill the resulted array.

For example

for ( size_t i = 0, j = 0; i < 3; i   )
{
    for ( size_t k = 0; k < quantity[i]; k   )
    {
        result[j  ] = element[i];
    }
}

CodePudding user response:

Firstly we need to calculate the size of the result array. Then start populating your result array each element at a time. While we populate the result array, we need to increment the index.

int elementSize = sizeof(element)/sizeof(element[0]);
int resultSize = 0;

//pre calculating the size of result array
for(int i=0;i<elementSize;i   ) {
    resultSize  = quantity[i];
}

int result[resultSize], currIndex = 0;
//picking each element
for(int i = 0;i< elementSize; i   ) {
    int currElement = element[i];
    int currQuantity = quantity[i];

//filling the current element required no of times in the result array
    while(currQuantity--) {
        result[currIndex] = currElement;
        currIndex  ;
    }
}

//just a for loop to check the elements inside result array
for(int i=0;i<resultSize;i  )
    printf("%d\n",result[i]);
  • Related