Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
This program demonstrates an algorithm for deleting duplicate values of type char in an array.
//This program demonstrates an algorithm for deleting duplicate values of type char in an array.
#include "stdafx.h"
#include <iostream>
using std::cout;
using std::endl;
void DeleteRepeats(char a[], int& numberUsed);
//Precondition: numberUsed is <= declared size of a. a[0] through a[numberUsed - 1] have values of type char.
//Postcondition: All duplicate values in a have been deleted, and numberUsed has been adjusted to reflect
//its appropriate value after any elements were deleted.
void Output(const char a[], const int numberUsed);
//Precondition: numberUsed <= declared size of a. a[0] through a[numberUsed - 1] have values of type char.
//Postcondition: Outputs a[0] through a[numberUsed - 1] with spaces between each.
void RemoveFromArray(char a[], int startingIndex, int& numberUsed);
//Precondition: numberUsed <= declared size of a. a[0] through a[numberUsed - 1] have values of type char.
//a[startingIndex] is the element to be removed from a.
//Postcondition: a[startingIndex] has been removed from the array.
//a[startingIndex + 1] through a[numberUsed] shifted one index left. numberUsed decremented by one.
void LineSpace();
//Ouputs endl twice.
int main()
{
int arraySize1 = 5;
int arraySize2 = 5;
char myArr1[] = { 'a', 'a', 'b', 'c', 'a' };
char myArr2[] = { 'x', 'y', 'y', 'z', 'x' };
DeleteRepeats(myArr1, arraySize1);
DeleteRepeats(myArr2, arraySize2);
Output(myArr1, arraySize1);
LineSpace();
Output(myArr2, arraySize2);
LineSpace();
return 0;
}
void DeleteRepeats(char a[], int& numberUsed)
{
for (int i = 0; i < numberUsed - 1; i++)
{
for (int j = i + 1; j < numberUsed; j++)
{
if (a[i] == a[j])
{
RemoveFromArray(a, j, numberUsed);
j--;
}
}
}
}
void Output(const char a[], const int numberUsed)
{
for (int i = 0; i < numberUsed; i++)
{
cout << a[i] << " ";
}
}
void LineSpace()
{
cout << endl << endl;
}
void RemoveFromArray(char a[], int startingIndex, int& numberUsed)
{
numberUsed--;
for (startingIndex; startingIndex < numberUsed; startingIndex++)
{
a[startingIndex] = a[startingIndex + 1];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment