Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- //fucntion adds a value to an array and expands the array if its full
- int* expand(int*, int, int&);
- //helper print function
- void print(int*, int);
- int main()
- {
- int* oldarr = 0;
- int length = 0;
- int input;
- do
- {
- cout << "Enter an integer: ";
- cin >> input;
- oldarr = expand(oldarr, input, length);
- print(oldarr, length);
- } while (input != -99);
- delete[] oldarr;
- oldarr = 0;
- cin.get();
- return 0;
- }
- int* expand(int* oldarr, int newvalue, int& length)
- {
- // dynamically create a new array that is length + 1
- int* newarr = new int[length + 1];
- // copy all the values from the old array to the new one
- for (int i = 0; i < length; i++)
- newarr[i] = oldarr[i];
- // add the new value to the end of the array
- newarr[length] = newvalue;
- // delete old array
- delete[] oldarr;
- length++;
- return newarr;
- }
- void print(int* arr, int length)
- {
- for (int i = 0; i < length; i++)
- cout << arr[i] << " ";
- cout << endl << endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement