sábado, 30 de noviembre de 2013

Arrays Problem Example (from Labs)

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.
For example, consider the following code:
char a[10];
a[0] = ’a’;
a[l] = ’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 input(char word[], int& size);
void delete_repeats(char word[], int& size);
 
int main()
{
  int size;
  char array[81];
  input(array,size);
  delete_repeats(array,size);
  cout << "resulting array: ";
  for( int i = 0; i < size; i++ ) {
    cout << array[i] << " ";
  }
  cout << endl << endl << endl;
  
  return 0;
}
void input(char word[], int& size)
{
  int counter = 0;
  cout << endl;
  cout << "counter = " << counter; //testing
  cout << endl;

  cout << "Please enter a word:\n";
 
  do
    {
     
      cin.get(word[counter]);
      cout << endl;
      cout << "counter = " << counter; 
      cout << ";  word[" << counter << "] = " << (int)word[counter]; //testing
      cout << endl;
      counter++; 
 
    }while (word[counter-1] != '\n'); 
  size = counter - 1;
  cout << size << " size"; 
  cout << endl;
  cout << endl;
  cout << "counter = " << counter; 
  cout << endl;
}
void delete_repeats(char word[], int& size)
{
  for (int i = 0; i < size; i++)
    {
 
      for (int j = i+1; j < size; j++)  
{
 if (word[i] == word[j])
   {
 
     for (int k = j; k < size - 1; k++) 
{
 
 word[k]= word[k + 1];
}
     
     j--;
     size--;
   } 
 cout << "size = " << size;
 cout << endl;
}
    }
}

No hay comentarios.:

Publicar un comentario