Not logged in. Log in with GitHub. About Websheets.

List of all available Websheets


Viewing cpp/dynamic_mem/ordered_array by redekopp@usc.edu. You have unsaved changes. Log in above to create, edit, preview and publish Websheets.
PropertyValue
Description
html markup
shown to student
 
Define a function <tt>ordered_array</tt> that takes a single integer argument,
<tt>n</tt> and dynamically allocates an integer array of that size and fills
it with values 1 through n.  It should return the dynamically allocated
array back to main which will print out its contents and perform any cleanup.
Public permissions remove
Remarks
Comments, history, license, etc.
 
Originally by Mark Redekopp (redekopp@usc.edu) and Dave Pritchard (daveagp@gmail.com)
remove
Engine
Template / Reference solution
 
#include <iostream>
using namespace std;
// return a new, dynamically allocated integer array of
//  size n with values 1 to n stored in it
\[int*]\ ordered_array(int n) {
    int* data = \[new int[n]]\;
   \[
   for (int i=0; i < n; i++) {
      data[i] = i+1;
   }
   ]\
    return \[data]\;
}
int main() {
   int n;
   cout << "Enter the size of the array: " << endl;
   cin >> n;
   // Select the right type for the nums value which stores
   //   what is returned by ordered_array()
   \[int*]\ nums = ordered_array(n);
   for (int i=0; i < n; i++) {
      cout << nums[i] << " ";
   }
   cout << endl;
   // Do any other final work before exiting
  \[
   delete[] nums; 
  ]\
   return 0;
}
C++ test suite
json list of stdin/args tests
e.g. [{"stdin":"hi", "args":["4", "5"]},
{"stdin":"noargs"}]

to just run once with no input use [{}]
 
[
   {"stdin": "5", "args": [""]},
   {"stdin": "1", "args": [""]}
]
Solution visibility remove


Optional properties:

Note: problems are open-source by default (see 'Public permissions'). Assumed license for open problems is Creative Commons 4.0 Attribution-ShareAlike unless specified in 'Remarks'.