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

Asked

Viewed 558 times

5

I have a problem that I have to assemble a vector (vet2[50]) with the sum of a large vector (vet1[100]), this vector vet1 is provided by the user and the sum if provided 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 make this sum, if the vectors were smaller I could do manual (method above), but as they are large I am half lost.

  • This vector is tiny. It would need more information. It would be good to put your code in the question and tell you where you are having trouble. But any size makes no sense to do one by one.

1 answer

5


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

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

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

In the sum loop I created each element of the second vector by summing 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).

For an exercise I think it’s good like this.

#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]);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.