fork download
  1. //Charlotte Davies-Kiernan CS1A Chapter 9 P. 537 #1
  2. //
  3. /*****************************************************************************
  4.  *
  5.  * Allocate Integer Array
  6.  * ___________________________________________________________________________
  7.  * This program will allocate an array of integers and display the sequence
  8.  * of integers up to the amount elements asked for, each element being squared.
  9.  * ___________________________________________________________________________
  10.  * Input
  11.  * number :number of elements to allocate
  12.  * Output
  13.  * allocateArray :function that creates the array and sends its address back to main
  14.  * myArray :a pointer that stores the address of the array and lets you access and modify it
  15.  *****************************************************************************/
  16. #include <iostream>
  17. #include <iomanip>
  18. using namespace std;
  19.  
  20. //Function Prototype
  21. int* allocateArray(int size);
  22.  
  23. int main() {
  24. int number;
  25. int* myArray;
  26.  
  27. //User Input
  28. cout << "Enter number of elements to allocate: " << endl;
  29. cin >> number;
  30.  
  31. //Call Function
  32. myArray = allocateArray(number);
  33.  
  34. //Print!
  35. for(int i = 0; i < number; i++){
  36. myArray[i] = (i + 1) * (i + 1);
  37. cout << myArray[i] << " ";
  38. }
  39. //Free Memory
  40. delete [] myArray;
  41.  
  42. return 0;
  43. }
  44.  
  45. //Function Definition
  46. int* allocateArray(int size) {
  47. int* arr = new int[size];
  48. return arr;
  49. }
Success #stdin #stdout 0.01s 5324KB
stdin
8
stdout
Enter number of elements to allocate: 
1 4 9 16 25 36 49 64