Write a function called delete_repeats that has a partially filled array of
characters as a formal parameter and that deletes all repeated letters from the array. Since a partially filled array requires two arguments, the function will actually have two formal parameters: an array parameter and a formal parameter of type int that gives the number of array positions used. When a letter is deleted, the remaining letters are moved forward to fill in the gap.
This will create empty positions at the end of the array so that less of the
array is used. Since the formal parameter is a partially filled array, a second
formal parameter of type int will tell how many array positions are filled.
This second formal parameter will be a call-by-reference parameter and will
be changed to show how much of the array is used after the repeated letters
are deleted.
Video Note
Solution to
Programming
Project 7.3
For example, consider the following code:
char a[10];
a[0] = 'a';
a[1] = 'b';
a[2] = 'a';
a[3] = 'c';
int size = 4;
delete_repeats(a, size);
After this code is executed, the value of a[0] is 'a', the value of a[1] is
'b', the value of a[2] is 'c', and the value of size is 3. (The value of a[3]
is no longer of any concern, since the partially filled array no longer uses
this indexed variable.)
You may assume that the partially filled array contains only lowercase
letters. Embed your function in a suitable test program.
#include <iostream>
using namespace std;
void delete_repeats(char a[], int size, int& number_used);
void output(char a[], int& number_used);
int main()
{
char array[100];
int number_used;
delete_repeats(array, 100, number_used);
output(array, number_used);
}
void delete_repeats(char a[], int size, int& number_used)
{
char c;
int index = 0;
cout << "Please type in a sentence and then press enter.\n";
cin.get(c);
while (c != '\n' && index < size) {
a[index] = c;
cin.get(c);
index++;
}
number_used = index;
cout << "\nThe size of the array is " << number_used << endl;
for (int i = 0; i < number_used; i++) {
for (int j = i + 1; j < number_used; j++) {
if (a[i] == a[j]) {
number_used = number_used - 1;
for (int k = j; k < number_used; k++)
a[k] = a[k + 1];
a[number_used] = '\0';
--j;
}
}
}
}
void output(char a[], int& number_used)
{
cout << "The new sentence without the repeated letters is:\n";
for (int i = 0; i < number_used; i++) {
cout << a[i];
}
cout << "\nThe new size of the array is " << number_used << endl;
cin.ignore();
cin.get();
}
Result output:
Please type in a sentence and then press enter.
Hello Peter
The size of the array is 11
The new sentence without the repeated letters is:
Helo Ptr
The new size of the array is 8