A Pair of Arrays – Solution

The challenge for this month’s Exercise is to initialize two different arrays to two sets of values. You should try to use only one loop and try to use a single statement to make the element assignments.

The first array alpha[] is initialized to values 1 through 50.

The second array beta[] is initialized to values 51 through 100.

The good news is that scant math is required to initialize the two arrays together; beta[]‘s elements are the same as alpha[]‘s plus 50. So a single loop that repeats 50 times can easily fill both arrays, as shown in this solution, which uses two statements in a for loop to initialize the element values:

2021_02-Exercise.c

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char alpha[50], beta[50];
    int x;

    /* initialize the arrays */
    for( x=0; x<50; x++)
    {
        alpha[x] = x+1;
        beta[x] = x+51;
    }

    /* output results */
    for( x=0; x<50; x++)
        printf("%2d\t%2d\n",alpha[x],beta[x]);

    return(0);
}

The for loop at Line 10 initializes both arrays:

alpha[x] = x+1;
beta[x] = x+51;

Because each element differs by 50, the math works on variable x to assign values 1 through 50 to alpha[] and 51 through 100 to beta[]. A printf() statement in a for loop at Line 17 outputs the results in two columns.

To make the assignments in a single statement, replace Lines 12 and 13 in my solution with this:

beta[x] = (alpha[x] = x+1) + 50;

Working from the inside out, the assignment is first made to alpha[x]. The result is added to 50, then assigned to beta[x]. The program’s output is the same.

I hope you enjoyed this Exercise, and that your solution generated the proper output. More power to you if you made the assignments in both a single loop and single statement.

2 thoughts on “A Pair of Arrays – Solution

Leave a Reply