How to access the indexes of a very large vector in C?

4

I have a problem that I have to mount a vector ( vet2[50] ) with the sum of a large vector ( vet1[100] ), this vector vet1 is provided by the user and the sum is given by:

vet2[0]=vet1[0]+vet1[1]

vet2[1]=vet1[2]+vet1[3]
.
.
.
vet2[49]=vet1[98]+vet1[99]

I can not establish a logic to do this sum, if the vectors were smaller would give to do manual (method above), but as they are large I am half lost.

    
asked by anonymous 09.10.2016 / 16:01

1 answer

3

You need to loop and vary the index by the loop variable.

I made an example with 6 numbers, but just switch to 100 on the second line. Do not put an odd value that will give problem.

I started the vectors by zeroing them, I made a loop to read all items, then I made the summation loop and finally the loop showing the result.

In the sum loop I have created each element of the second vector by adding the equivalent elements according to the formula apparently requested in the question (it is not easy to do something without a formula definition, but I am confident that this is what you want) p>

For an exercise I think it feels good.

#include <stdio.h>
#define MAX 6

int main(void) {
    int vet1[MAX];
    int vet2[MAX / 2];
    for (int i = 0; i < MAX; i++) {
        scanf("%d", &vet1[i]);
    }
    for (int i = 0; i < MAX / 2; i++) {
        vet2[i] = vet1[i * 2] + vet1[i * 2 + 1];
    }
    for (int i = 0; i < MAX / 2; i++) {
        printf("%d\n", vet2[i]);
    }
}

See working on ideone and C ++ Shell >.

    
09.10.2016 / 16:21