dynamic array: sum of first and last number

hey everyone I am currently working on a homeworking that requires using dynamic arrays.
it is supposed to take in numbers and stops when it reads a negative one.
It has to calculate the sum of the first and the last number(not negative)in the array then calculates the second and the second last and so on...
the remaining number has to be dubbled.

for example: 4 3 5 1 7 -1
output: 11,4,10.
im always getting negative rubish with this code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
int input;
int count = 1;
int *table = new int[count];

do {
 cout << "input" << count << " :";
 cin >> input;
count++;

int*temptable = new int[count];

for (int i = 0; i < count; i++) {
temptable[i] = table[i];}
		
delete[]table;
table = temptable;
} while (input > 0);

cout << "show row: ";
for (int i = 0; i < count/2; i++) {
int answer=table[i] + table[count - 2-i];
cout << answer << ", ";}
	
delete[]table;
table = nullptr;
	}
Last edited on
a dynamic array is not a suitable container for this exercise, what if a negative number is not entered before the array runs out of size? can you use std::vector?
edit:
it is supposed to take in numbers and stops when it reads a negative one.

to make it work with a dynamic array this condition has to be an either or - either it reads a negative one or it runs out of size
Last edited on
The first problem is that you do not store input in the array.
The second problem is line 12: For table it is out of bounds.

I suggest the following:
1
2
3
4
5
6
7
8
9
10
count++;

int*temptable = new int[count + 1];

for (int i = 0; i < count; i++) {
temptable[i] = table[i];}

temptable[count] = input;

count++;


You need additional code for the last negative number. Either an if or you simply decrement count after the input loop.
Last edited on
thanks I'll following your advice, i now understand my mistake. But will it not affect the answer when calculating the remaining number of the array without the negative number?
Last edited on
According to this:
It has to calculate the sum of the first and the last number(not negative)in the array
The negative number needs to be left out of the calculation.

EDIT:
Line 2 is also a problem. This would include one uninitialized field (the very first). Change to:
1
2
int count = 0;
int *table = nullptr; // It is not a problem to delete nullptr 
Last edited on
ah I forgot this detail, thanks
Topic archived. No new replies allowed.