Arrays Introduction

  • + 0 comments

    //Dynamic allocation of an array

    int *arrPtr{}, userInput{};
    
    cin >> userInput; 
    arrPtr = new int[userInput]; //allocate array at runtime
    
    for(size_t i{1}; i<=userInput; i++) { 
    	cin >> arrPtr[i-1]; //store elements starting at index 0
    }
    
    for(size_t j{1}; j<=userInput; j++) {
    	cout << arrPtr[userInput-j] << " ";
    }
    
    delete [] arrPtr; //free allocated storage (good practice)
    

    //Pre-defined array with a fixed size (based on constraints)

    int userInput{}, arrFixed[1000]{};
        
    cin >> userInput;
        
    for(size_t i{1}; i<=userInput; i++) {
    		cin >> arrFixed[i-1]; 
    }
    
    for(size_t j{1}; j<=userInput; j++) {
    		cout << arrFixed[userInput-j] << " ";
    }