Hello! I'm doing an exercise which involves for the user to enter the size of the dynamic array and then enter the numbers, but then it needs to create another dynamic array with the same numbers expect if the number repeats it only has one of it.
I've done the first part of the exercise but I'm having trouble with creating the new array. Any help?
you would need to loop though each element and compare it with all the others. if it doesn't match any other element, you increment a counter and store the value.. you then use the counter as the size of the new array. When you copy the contents of the array over to the new one, compare each element from the old array to the stored entities. If it matches, don't copy it over.
@pogrady: you have not even determined which scenario he actually needs. If he needs the first, it is much simpler. If he needs the second, it is still much simpler than you have made it out ;)
In that case, your task is a bit more complicated.
Are you allowed to use any classes from the Standard Template Library? E.g. std::vector, std::set, etc. - if you are, just use a std::set and it will automatically do this for you.
I'm going to assume you're not allowed to though. In this case, you need to use nesting. The outer loop will be looping through the normal array - just take the element and see what it is. Then the inner loop will be going through what you have so far in the new array - obviously the first time it will loop 0 times because you have nothing in the new array.
All you have to do is keep track of how many numbers you have put into the new array as you go through it. In your inner loop when you find a match, that means you already have that number in there. If you get through the entire inner loop and have not found a match, then the number is not yet in there and you can add it in.
Try writing as much as you can and if you get stuck post with what you have written.
#include <iostream>
usingnamespace std;
int main()
{
int*p;
int *np;
int size;
int nsize;
cout<<"Enter the size of the array => ";
cin>>size;
p=newint [size];
nsize=size*2;
for ( int i = 0; i < size; i++){
cout << "Enter number => ";
cin >> * ( p + i );
}
np=newint [nsize];
cout<<"Your array: ";
for(int i=0; i<size; i++)
cout<<*(p+i)<<" ";
cout<<endl;
cout<<"2nd array: ";
return 0;
}
I'm not really sure what to write to keep track of the numbers in the first array.
@pogrady: you have not even determined which scenario he actually needs. If he needs the first, it is much simpler. If he needs the second, it is still much simpler than you have made it out ;)
Your post wasn't there when I typed that.
Wouldn't the program still need to loop through and determine repeated numbers?