vendredi 2 novembre 2018

C - Rewriting a 2 for loop into a 1 for loop for copying arrays.

I was given the following problem:

"In function main declare an integer array called num1 with 30 elements and declare a second integer array called num2 with 21 elements. To each element of num1 assign a random number between 1 and 50; print the numbers.

In a for loop, copy the first 21 numbers from num1 to num2.

In another for loop print the element values from num2, seven values per line. Find an algorithm that will print them from one loop, not 3 loops. "

I have been able to narrow down to 2 for loops, but I am having difficulty trying to get everything into one for loop. I'm just not sure how I can copy the arrays from num1 into num2, if I don't use a second for loop.

Here is the work I've done so far. It prints everything correctly, but it's in 2 for loops and not 1.

for (j = 0; j < 30; j++) // getting random numbers for num1
{
    num1[j] = 1 + rand() % (50 + 1 - 1);
    printf("%d ", num1[j]);

}
printf("\nThis is num2:\n"); 
for (j = 0; j < 21; j++) // copying num1 array into num2 array, and only taking the first 21 numbers
{
    num2[j] = num1[j];
    printf("%d ", num2[j]);
    if (x % 7 == 0) // this will print num2 with 3 rows each with 7 values 
    {
        printf("\n");

    }
    x++;
}




Aucun commentaire:

Enregistrer un commentaire