Home > Net >  C How to add two arrays of unequal sizes using the for loop?
C How to add two arrays of unequal sizes using the for loop?

Time:03-17

So the aim is to take two arrays as shown below

int x[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int k[4] = {1, 2, 3, 4};

and add each element of k to each element of x in a loop as shown

 1  2  3  4  5  6  7  8  9  10
 1  2  3  4  1  2  3  4  1   2

This should give us a final array [2, 4, 6, 8, 6, 8, 10, 12, 10, 12].

Any suggestions as to how I could achieve this in C

CodePudding user response:

Loop through the indexes of the larger array, using the modulus (%) operator to wrap-around the indexes when accessing the smaller array.

int x[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int k[4] = {1, 2, 3, 4};
int res[10];
for (int i = 0; i < 10;   i) {
    res[i] = x[i]   k[i % 4];
}

Online Demo

CodePudding user response:

With % you can have the wrap-around behavior and with std::size(from C 17 onwards) the size of the array.

#include <algorithm>
#include <iostream>
int main()
{
   int x[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
   int k[4] = {1, 2, 3, 4};
   for(int i = 0; i < std::size(x);   i)
   {
       x[i] = x[i]   k[i%std::size(k)];
   }

    //lets confirm if x has the right elmennts 
    for(const int& element: x)
        {
            std::cout<< element<<std::endl;
        }
}

Note that here i have not used a separate array to store the resulting array. Instead the elements are added into the original array x. Storing the result in a new array is trivial.

  • Related