Paul Filch
Paul Filch

Reputation: 917

Trouble getting an array in sets program (C)

I am working on a C program that deals with sets, and I am having trouble getting the values for an array in my C program. I am thinking that there is a logical error in the function below.

sizeA is 26, and setA is a boolean set of size 26.

Here is how the function should turn out if sizeA is 5:

Enter the first element in Set A: //user enters h

Enter the next element of Set A: //user enters i

Enter the next element of Set A: //user enters j

Enter the next element of Set A: //user enters k

Enter the next element of Set A: //user enters l

fffffftttttffffffffffffff

However it turns out like this if sizeA is 5:

Enter the first element in Set A: //user enters h

Enter the next element of Set A: //user enters i

Enter the next element of Set A: //user enters j

Enter the next element of Set A: //user enters k

Enter the next element of Set A: //user enters l

ffffff 

I would like to know how to fix this problem.

Here is the code:

void getSetA(bool setA[], int sizeA)
{
      letters element, letter;
      int position = 0, num, i;

      for(i = 0; i < sizeA; i++)      //sizeA is inputted before
      {
            setA[i] = FALSE;      
      }
      printf("\nEnter the first element in Set A: ");
      element =  getcharNoBreaks();
      if (element >= 'a' && element <= 'z') 
      {
              setA[element-'a'] = TRUE;
      }
      for(num = 1; num < sizeA; num++)
      {
            printf("\nEnter next element of Set A: ");
            element =  getcharNoBreaks();
            if(element >= 'a' && element <= 'z')
            {
                       setA[element - 'a'] = TRUE;          
            }
            else       printf("Element out of range");
      }
      printf("\n");
      for(i = 0; i < sizeA; i++)
      {
            if(setA[i] == TRUE) printf("t");   
            else                printf("f");     
      }      
}

Note that letters, is a type I have defined (as all the letters of the alphabet), and getcharNoBreaks() is a function that is equivalent to getchar().

Thank you :)

Upvotes: 0

Views: 70

Answers (2)

Lidong Guo
Lidong Guo

Reputation: 2857

So , 'h' - 'a' = (int) 7 and if 'z' - 'a' = 25. Right? Question is :

. Is ths size of setA big enough?

If it a big array . Add printf("intput c is :%c\n",element); You should check what elem really was indeed.

Upvotes: 1

spin_eight
spin_eight

Reputation: 4025

void getSetA(bool setA[], int sizeA) - sizeA should be 26. everything else looks fine.

As i understood you program works with set of english letters a..z, user enters some letters that will be enabled - for them true flag will be set.

Upvotes: 1

Related Questions