Search code examples
c++arraysalgorithmvectorreverse

I wanted to reverse my array. Why this code gives garbage value?


    #include <iostream>


    using namespace std;

    int main(){

    int n;
    int a[n];
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>a[i];
    }
    for(int i=n;i>=0;i--){
       cout<<a[i]<<" ";
   }
    }

Input:- 4 1 2 3 4 Output 4199008 4 3 2 1


Solution

  • For starters the program has undefined behavior because the variable n is not initialized

    int n;
    

    So this declaration

    int a[n];
    

    is invalid. Moreover variable length arrays is not a standard C++ feature. Instead use the standard class template std::vector.

    Also within this loop

    for(int i=n;i>=0;i--) {
       cout<<a[i]<<" ";
    }
    

    you are trying to access of non-existent element with the index n.

    Also you are not reversing an array. You are trying to output an array in the reverse order.

    Pay attention to that there are standard algorithms std::reverse and std::reverse_copy declared in the header <algorithm>.

    Here is an example how your program with using your approach could look

    #include <iostream>
    #include <vector>
    
    int main() 
    {
        size_t n = 0;
    
        std::cout << "Enter the size of an array ";
    
        std::cin >> n;
    
        std::vector<int> v( n );
    
        std::cout << "Enter " << n << " elements: ";
    
        for ( auto &item : v ) std::cin >> item;
    
        std::cout << "The array in the reverse order\n";
    
        for ( size_t i = v.size(); i != 0;  )
        {
            std::cout << v[--i] << ' ';
        }
        std::cout << '\n';
    
        return 0;
    }
    

    The program output might look like

    Enter the size of an array 10
    Enter 10 elements: 0 1 2 3 4 5 6 7 8 9
    The array in the reverse order
    9 8 7 6 5 4 3 2 1 0 
    

    If to use standard algorithms then your program can look the following way

    #include <iostream>
    #include <vector>
    #include <iterator>
    #include <algorithm>
    
    int main() 
    {
        size_t n = 0;
    
        std::cout << "Enter the size of an array ";
    
        std::cin >> n;
    
        std::vector<int> v( n );
    
        std::cout << "Enter " << n << " elements: ";
    
        std::copy_n( std::istream_iterator<int>( std::cin ), n, std::begin( v ) );
    
        std::cout << "The array in the reverse order\n";
    
        std::reverse_copy( std::begin( v ), std::end( v ), 
                           std::ostream_iterator<int>( std::cout, " ") );
        std::cout << '\n';
    
        return 0;
    }
    

    The program output might look the same way as shown above

    Enter the size of an array 10
    Enter 10 elements: 0 1 2 3 4 5 6 7 8 9
    The array in the reverse order
    9 8 7 6 5 4 3 2 1 0