Add two array columns having two different lengths



  • Hi There,
    This might be easy but i am struggling to get it right
    I got two arrays, Let's say
    a[10] = {0,1,2,3,4,5,6,7,8,9} b[20]={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19} now i want to add first 10elements of 1st array with first 10elements of the 2nd array and 1st 10elements of the first array with 2nd 10elements of the 2nd array and so on, the result should be look like 0,2,4,6,8,10,12,14,16,18,10,12,14,16,18,20,22,24,26,28. so far what i have done is like following

    @int i,j;
    float a[10];
    float b[20]
    int result;
    for(i=0,j=0;i<10,j<20;i++,j++){
    a[i] = i;
    b[j] = j;
    result = a[i] + b[j];
    printf("%d\n",result);
    }@

    and the result of this looks like following 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38
    first 10 columns were added up correctly but not the 10elements of the first array and 2nd 10elements of the 2nd array.

    Could someone please help me how to fix this, an Example would be good.

    Thanks inadvance


  • Moderators

    Hi,

    Do you want to store your result in an array, or do you just want to print it?

    [quote author="pushpa416" date="1423111890"]
    @
    for(i=0,j=0;i<10,j<20;i++,j++){
    @
    [/quote]When do you want the loop to stop?

    The middle part must only contain 1 boolean expression. However, "i<10" and "j<20" are two separate expressions; one of them will be ignored.

    [quote author="pushpa416" date="1423111890"]
    @
    a[i] = i;
    b[j] = j;
    result = a[i] + b[j];
    printf("%d\n",result);
    @
    [/quote]I suggest you print out the values of a[i] and b[i] too. That should give you a clue.



  • How about something like:

    @
    template<class ForwardIterator, class RandomIterator, class Function>
    int arrayOperation(ForwardIterator first, ForwardIterator last, RandomIterator argFirst, RandomIterator argLast, Function fn)
    {
    RandomIterator::difference_type argLen = argLast - argFirst;
    int i(0);
    while (first!=last) {
    (*first) = fn (*first, (*argFirst + (i % argLen)));
    ++first; ++i;
    }
    return i;
    }
    @

    and then call:

    @
    arrayOperation(a[0],a[19],b[0],b[9],std::plus);
    @

    This will store the result of the addition back in array a. Code not tested of course.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.