Advertisement
Guest User

Untitled

a guest
Jun 28th, 2015
353
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.02 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. //fucntion adds a value to an array and expands the array  if its full
  6. int* expand(int*, int, int&);
  7.  
  8. //helper print function
  9. void print(int*, int);
  10.  
  11. int main()
  12. {
  13.     int* oldarr = 0;
  14.     int length = 0;
  15.     int input;
  16.  
  17.     do
  18.     {
  19.         cout << "Enter an integer: ";
  20.         cin >> input;
  21.  
  22.         oldarr = expand(oldarr, input, length);
  23.         print(oldarr, length);
  24.  
  25.     } while (input != -99);
  26.  
  27.     delete[] oldarr;
  28.     oldarr = 0;
  29.  
  30.     cin.get();
  31.     return 0;
  32. }
  33.  
  34. int* expand(int* oldarr, int newvalue, int& length)
  35. {
  36.     // dynamically create a new array that is length + 1
  37.     int* newarr = new int[length + 1];
  38.  
  39.     // copy all the values from the old array to the new one
  40.     for (int i = 0; i < length; i++)
  41.         newarr[i] = oldarr[i];
  42.  
  43.     // add the new value to the end of the array
  44.     newarr[length] = newvalue;
  45.  
  46.     // delete old array
  47.     delete[] oldarr;
  48.  
  49.     length++;
  50.  
  51.     return newarr;
  52. }
  53.  
  54. void print(int* arr, int length)
  55. {
  56.     for (int i = 0; i < length; i++)
  57.         cout << arr[i] << " ";
  58.     cout << endl << endl;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement