Hi guys,
I am currently working on a practical for a first year computing subject. I am determined to work it out because I think it will really unlock pointers and dynamic memory allocation for me. Essentially, the task requires that I produce a program which, when prompted, will store series of numbers in an array, "growing" as necessary.
Here is sample input/output:
How many numbers? 4
Enter the numbers: 2 6 4
How many numbers? 3
Enter the numbers: 23 5 -2
How many numbers? 0
The total numbers entered are: 2 6 4 23 5 -2
I have produced what must be a competitor for "World's Worst Piece of Code". Here it is:
#include <iostream>
using namespace std;
void grow(int array[], int newnumber, int oldsize);
int main()
{
int n; // how many numbers?
int t; // the numbers
int current = 0; // current size of array
bool flag = true; // flag to control loops
// create initial array
int *array = new int[current];
int j = 0; // a counter
int count = 0; // determine whether all of the numbers have been entered
while (true)
{
cout << "How many numbers?" << endl;
cin >> n;
if (n <= 0)
{
for (int i = 0; i < current; i++)
cout << array[i] << endl;
break;
}
grow(array, n, current);
cout << "Enter the numbers?" << endl;
while (cin >> t && flag == true)
{
array[j] = t;
count++;
if (count == n)
flag = false;
}
}
return 0;
}
void grow(int array[], int newnumber, int oldsize)
{
int newsize = oldsize + newnumber; // determine size of new array
int *temp = new int[newsize];
// copy old data into temp
for (int i = 0; i < oldsize; i++)
temp[i] = array[i];
// set the newly added elements to zero
for (int i = oldsize; i < newsize ;i++)
temp[i] = 0;
// delete array
delete [] array;
array = temp; // swap contents back to array
}
I guess there are a couple of issues going on here:
1 - The ability of the grow function to perform properly.
2 - The way that I have used the control structures, which I know is *terrible*.
I really am keen to improve my understanding, so any help would be greatly appreciated.
Cheers,
Daniel