0

i have problem with my code. the program should print tab backwards but it gives also additional numbers example:

7  6  8  7  2  1    6 1 2 7 8 6 7
#include<iostream>
#include<ctime>

int main()
{
    using namespace std;
    srand(time(nullptr));
    
    int tab[6];
    
    for (int i = 0; i < 6; i++)
    {
        tab[i] = rand() % 8 + 1;
        cout << " " << " " << tab[i];
    }
    
    cout << "   ";
    for (int i = 6; i >= 0; i--)
    {
        cout << " " << tab[i];
    }
user4581301
  • 33,082
  • 7
  • 33
  • 54

1 Answers1

2
for (int i = 6; i >= 0; i--)

Should be:

for (int i = 5; i >= 0; i--)

Because i cannot be over 5, there's not that many elements

Edit: As suggested in the comments, this is a bit more legible. It assumes it's a constant size array though, it does not work for a dynamic array.

for (int i = sizeof(tab) / sizaof(tab[0]) - 1; i >= 0; i--)
IWonderWhatThisAPIDoes
  • 1,000
  • 1
  • 4
  • 14