Print components of an array in reverse order

Asked

Viewed 1,476 times

0

I wrote a code to print the components of a array in reverse order. However, it only returns 5 or 6 numbers (at most), even if I have put more numbers in it.

#include <iostream>
using namespace std;


int main()
{

    int i;
    int vet[i];

    cin >> i; /*Tamanho do array*/

    for(int t = 0; t<i; t++) /*Adiciona coisas no array*/
    {
        cin >> vet[t];
    }

    for(int f = i-1; f>=0; f--) /*Imprime o que tem dentro do array em ordem inversa*/
    {
        cout << vet[f] << " ";
    }

}

Is there anything missing?

  • Can you print an example? I think the code is correct.

2 answers

3


Watch this:

    int i;
    int vet[i];

    cin >> i; /*Tamanho do array*/

That is, you declare the size of the array before reading this size. It should be later.

Try to do so:

#include <iostream>
using namespace std;

int main()
{

    int tamanho;
    cin >> tamanho; /*Tamanho do array*/
    int vet[tamanho];

    for (int t = 0; t < tamanho; t++) /*Adiciona coisas no array*/
    {
        cin >> vet[t];
    }

    for (int f = tamanho - 1; f >= 0; f--) /*Imprime o que tem dentro do array em ordem inversa*/
    {
        cout << vet[f] << " ";
    }
}

Note that I renamed the variable i for tamanho. Giving variables good names is important.

See here working on ideone.

  • kkkk I will adopt this custom!!! Thanks Victor!!!

  • @Miguelteixeira If my answer helped you and there is no doubt left, mark it as accepted by clicking on " " on the left. This also marks your question as answered/solved. If you have any further questions, you can leave a comment.

2

The big problem is you’re declaring array before knowing what is the desired size for it. So first ask how many elements it should have, then declare with the informed size.

#include <iostream>
using namespace std;

int main() {
    int i;
    cin >> i;
    int vet[i];
    for (int t = 0; t < i; t++) cin >> vet[t];
    for (int f = i - 1; f >= 0; f--) cout << vet[f] << " ";
}

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

  • First I declared a variable with the name "i", then I declared an array with the "amount of elements i". So, theoretically, when I don’t set the "size" of i, does the array already reserve a kind of maximum size that it can have when allocated to memory? Because I noticed that the code worked up to a certain number of elements, and when exceeding that amount, either an error occurred or it printed on the screen a smaller number of elements than i (in the reverse order).

  • No, it’s worse, it uses junk that’s in memory as a value, at least that’s how it is in C/C++. If you run under different conditions the number will change, it is virtually random.

  • Got it!! Thanks Maniero!!!

Browser other questions tagged

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