Problem with neighboring positions in C++ arrays

Asked

Viewed 80 times

0

#include <iostream>

using namespace std;

int main(){
    int myVector[] = {2,6,4,1,9,5,7,3,8,0};
    int tamanhoVetor = sizeof(myVector)/sizeof(myVector[0]);

    //Imprime
    for (int i=0; i<tamanhoVetor-1; i++){
        cout << myVector[i+1] << ", ";
    }

    return 0;
}

The expected would be:

6, 1, 5, 3, 0

but he returns:

6, 4, 1, 9, 5, 7, 3, 8, 0

I did not understand why it occurs this, I tried to do the same thing in Python, only that the same problem occurs. Probably the mistake is in my logic.

  • The variable sizeVetor is with the value 10, its starts at 0 and always prints the loop plus one, so you end up printing all the values of your vector, except for the first position.

  • If you want to skip numbers in the for, you can increase the increment of the same, increase for example two each cycle: for (int i=0; i<sizeVetor-1; i+=2)

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

2 answers

1

A pity to be using C in a C++ code, should not do this. C++ to use array or vector and not the pointer that simulates array of C. If you made C++ you wouldn’t have this error.

Really your logic is wrong, you should jump 2 by 2 and not jump 2 by 1 and add 1 like you did, and simplify would look like this:

#include <iostream>
using namespace std;

int main() {
    int myVector[] = {2,6,4,1,9,5,7,3,8,0};
    for (int i = 0; i < sizeof(myVector) / sizeof(myVector[0]); i += 2) cout << myVector[i+1] << ", ";
}

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

0

One solution is to increment before printing. The addition operation within the vector did not work. As below:

#include <iostream>

using namespace std;

int main(){
    int myVector[] = {2,6,4,1,9,5,7,3,8,0};
    int tamanhoVetor = sizeof(myVector)/sizeof(myVector[0]);

    //Imprime
    for (int i=0; i<tamanhoVetor-1; i++){
        i++;
        cout << myVector[i] << ", ";
    }

    return 0;
}

Browser other questions tagged

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