Search code examples
arrayscfor-loopnested-loopsvariable-length-array

How do I solve this array problem in C language?


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?


Solution

  • 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];
        }
    }