Print components from an array in reverse order

0

I wrote a code to print the components of an array in reverse order. However, it only returns 5 or 6 numbers (at most), even though 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 anything missing?

    
asked by anonymous 29.09.2017 / 16:04

2 answers

3

Notice 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 this:

#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 to tamanho . Giving good names to variables is important.

See here working on ideone.

    
29.09.2017 / 16:18
2

The big problem is that you are declaring the array before you know what size you want for it. Then first piece out how many elements it should have, then declare it with the size informed.

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

See running on ideone . And in Coding Ground . Also I put GitHub for future reference .

    
29.09.2017 / 16:20