Tuesday, July 14, 2009

How do i add values to an array in C++ using a function.?

I have a set of values that i read into an array using a function earlier on, now i need to add additional values to the end of the array. hot do i go about doing that.

How do i add values to an array in C++ using a function.?
probably u had used a loop for earlier reading ,


then here's how it goes . i'll show an example.


#include%26lt;iostream.h%26gt;


void main()


{int a[20],i,n,m;


cout%26lt;%26lt;"\n How many elements ?";


cin%26gt;%26gt;n;


for(i=0;i%26lt;n;i++)


{


cin%26gt;%26gt;a[i];


}


cout%26lt;%26lt;"\n How many elements do you want to add ?";


cin%26gt;%26gt;m;


for(;i%26lt;n+m;i++)


cin%26gt;%26gt;a[i];


}





the idea here is , u hav executed for loop for the first reading , so u dont change the value of i that ws updated when it ws in the loop. Further reading takes place frm wer it ws stopped. Bt ur array size should be such that it can accomodate m+n elements
Reply:These are some way you can do


1. new array with maximize size array[MAX] and int _array_len variable.


Ex: len = 2;


buffer = new[len];


//TODO: init value


when u want to add value then just increase len++


buffer[len++] = value;


2. You should use collection like List or ArrayList





I hope it can help


No comments:

Post a Comment