I\'ll put the code below, but basicaly instead of a normal array, I need to use
ID: 638396 • Letter: I
Question
I'll put the code below, but basicaly instead of a normal array, I need to use a dynamic array. I have this program and it works fine but when ever I try to put use a dynamic array I mess it all up. Any help would be awesome, and maybe a some pointers on dynamic arrays because im kind of confused but ill be happy with just the help on the program. Thanks
#include <iostream>
#include <string>
using namespace std;
void delete_repeats(char[],int&);
?
int main()
{
char a[8]={'a','b','a','c','a','c','d','a'};
int count=8,i;
cout<<"starting array: ";
for(i=0;i<count;i++)
cout<<a[i]<<" ";
cout<<endl;
delete_repeats(a,count);
cout<<"ending array: ";
for(i=0;i<count;i++)
cout<<a[i]<<" ";
cout<<endl;
system("pause");
return 0;
}
void delete_repeats(char a[],int& n)
{
int i,j,k;
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
if(a[i]==a[j])
{for(k=j;k<n-1;k++)
a[k]=a[k+1];
n--;
j--;
}
}
Explanation / Answer
#include <iostream>
#include <string>
using namespace std;
void delete_repeats(char[],int&);
int main()
{
int n,count;
int * a;
cout << "How many numbers would you like to type? ";
cin >> count;
a= new (nothrow) int[count];
if (a == nullptr)
cout << "Error: memory could not be allocated";
else
{
for (n=0; n<count; n++)
{
cout << "Enter number: ";
cin >> a[n];
}
}
cout<<"starting array: ";
for(i=0;i<count;i++)
cout<<a[i]<<" ";
cout<<endl;
delete_repeats(a,count);
cout<<"ending array: ";
for(i=0;i<count;i++)
cout<<a[i]<<" ";
cout<<endl;
system("pause");
return 0;
}
void delete_repeats(char a[],int& n)
{
int i,j,k;
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
if(a[i]==a[j])
{for(k=j;k<n-1;k++)
a[k]=a[k+1];
n--;
j--;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.