Arrays question

I have a question that made me crazy :
My question might not be doable.
if i have an int array of size 20 , EX int array [20];
and i want to keep adding to this array till i get to the 20.
for example , i want to say :
add(2);
prints: 2
add(4);
prints : 2,4
add(5):
prints:2,4,5
..etc
NOTE:I CANNOT use vector
what I did is :
void add(int y)
{
static int size = 0 ;
size++;
int array[20];
int x= 0 ;
while (x<size)
{
array[x]= y ;
x++;
}
}
when they gets printed , i get repeated values :
My code code might be a complete junk because i am a beginner, and i just learn about arrays.
closed account (48T7M4Gy)
Use a terminal value to terminate the list. What this means if the list is to be positive integers make the terminal value -1.

So, in principle ...
- the list starts with list[0] = -1
- enter 6 so list becomes 6, -1
- enter 5 list becomes 5, 6, -1

- at each stage print out elements while not -1

In practice, even though the number of elements in the is limited to 20, a separate count variable could be used to keep track other actual number of items in the list.
There are two big issues that jump out at me:

1) You call add multiple times, but array is local to add so it doesn't retain the values from the previous call.

2) You write the same value to every element of array from 0 to size -1, which is why you keep getting the same value over and over again. All you need to do is array[size] = y; then increment size (or do both at the same time: array[size++] = y;).
Topic archived. No new replies allowed.