Arrays Introduction

  • + 2 comments

    Great solution by 'jorgechiquinv', adding some comments for posterity if you're rusty with C++ like me :-)

    #include <iostream>
    using namespace std;
    
    
    // Every C++ program starts with the main method
    int main() {
    
        // Declare a variable, N for the number of 
        // values entered in from stdin
        int N;
        // Declare a variable i for incrementing 
        int i=0;
        // Read in the initial value from cin into N, 
        // for the number of elements in the array
        cin>>N;
        // Declare a pointer of type int, called A, 
       // and allocated new memory for it of size N
        int *A = new int[N];
        
        // Setup a while loop for as long as cin 
        // is reading in variables, all into the array, A
        while(std::cin>>A[i++]);
        
        // Setup another while loop to output (cout) every 
        // value in A in reverse, using --N to decrement the 
        // the value of N so long as N is true (not equal to zero)
        while(std::cout<<A[--N]<<' ' && N);
    
        // Un-allocate the memory given to A
        delete[] A;
        
        // Return zero to indicate success
        return 0;
    }