Thread: An easy assignment...little help please!

  1. #1
    Registered User
    Join Date
    Apr 2005
    Posts
    67

    An easy assignment...little help please!

    Okej, my first homework is to open a file for reading and count all the letters from a-z, and the capitals and small are the same. So 'a' and 'A' is the same. I have to count how many of each letters are in this file.

    This is my codebut didn't include for all the letters)

    Code:
     #include<stdio.h>
    #include<stdlib.h>
    
    
    int main(int argc, char *argv[]) 
    
    {
      int br;
      int a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,r,s,t,u,v,z=0;
      
      FILE *datoteka;
     
    
      if(argc<2)
        {
           printf("Napisati morate argument-ime datoteke!");
           exit(1);
        }
     
      datoteka=fopen(argv[1],"r");
    
      while ((br=fgetc(datoteka)) !=EOF)
        {
          switch(br)
    	{
    	case 'a':
            case 'A': a++;
    	  break;
            case 'b':
            case 'B': b++;
    	  break;
    	  case 'c':
            case 'C': c++;
    	  break;
    	  case 'd':
            case 'D': d++;
    	  break;
    	  case 'E':
            case 'e': e++;
    	  break;
    	  case 'F':
            case 'f': f++;
    	  break;
    	  case 'g':
            case 'G': g++;
    	  break;
    	  case 'h':
            case 'H': h++;
    	  break;
    	  case 'i':
            case 'I': i++;
    	  break;
    	  case 'j':
            case 'J': j++;
    	  break;
    	  case 'k':
            case 'K': k++;
    	  break;
    	  case 'l':
            case 'L': l++;
    	  break;
    	  case 'm':
            case 'M': m++;
    	  break; //and so on to letter Z
    
         
            }
        }
       fclose(datoteka);
       printf("A:%d B:%d C:%d ....and so on\n",a,b,c);
       return 0;
    
    
    }
    Now, the above code does the job, but I have this feeling that this can be done with a lot less code. Any suggestions?

  2. #2
    Registered User
    Join Date
    Feb 2005
    Posts
    21
    There is one thing that can really minimize the work. Letters can be converted to numbers. So if you have 'A' - 'A' you have then number 0. So my suggestion would be to fill the array like this...
    Code:
    for(ch = getc(inp); ch != EOF; ch = getc(inp), next_pos)
    	      input[next_pos] = ch;
    Then you can simply increment the letters in the input array like this...
    Code:
    //number_let is the total number of letters
    for(i = 0; i < num_let; i++)
    	{	
    		//read the current character in the array
    	        in_char = in_array[i];
    		
    		
    		
    		//take the current character and subtract 'A' which is equal to 1. 
    		letters[in_char - 'A'] +=1;
    	
    	}
    }
    hope this helps...

  3. #3
    Registered User
    Join Date
    Feb 2005
    Posts
    21
    However, this may be quite confusing if you haven't even touched arrays yet. It took me forever to understand this stuff. there is also another command you might want to check out called toupper(). instead of listing cases for upper and lower cases you could change the input to all upper cases and then only have to do a switch for upper case letters. toupper() requrires ctype.h to be included.

  4. #4
    Work in Progress..... Jaken Veina's Avatar
    Join Date
    Mar 2005
    Location
    Missouri. Go Imos Pizza!
    Posts
    256
    Well, first you could use an array of ints, having each element represent a single value.
    Code:
    int lettercounts[26];
    int index;
    for(index = 0; index < 26; ++index)
      lettercounts[index] = 0;
    Then, I would suggest using a single if statement to determine if the entry is a lowercase or capital letter (or you could use the predefined function IsLetter.....or something similar, I don't know if that's exactly right. You can look it up). Then develop an algorith that modifies the interger value of the character into the index of the array and adds to that. It's kinda hard to explain, so I'll show you an example.
    Code:
    while((br = fegtc(datoteka)) != EOF)
     {
      if(br >= 'a' && br <= 'z')
        ++lettercounts[br - 97];
      else if(br >= 'A' && br <= 'z')
        ++lettercounts[br - 65];
      else
       {
        printf("Invalid entry!\n");
        return 0;
       }
     }
    Go with that. Then just loop through the array again with index and print each value.

  5. #5
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    For character sets in which the alphabet is contiguous, you can take advantage of this mathematical relationship, as acidbeat311 and Jaken Veina have pointed out while I was composing this.
    Code:
       if ( file )
       {
          size_t i;
          int letter[26] = {0};
          for ( ;; )
          {
             int c = fgetc(file);
             if ( c == EOF )
             {
                break;
             }
             if ( isalpha(c) )
             {
                ++letter[toupper(c) - 'A'];
             }
          }
          fclose(file);
          for ( i = 0; i < sizeof letter / sizeof *letter; ++i )
          {
             printf("'%c' : %d\n", i + 'A', letter[i]);
          }
       }
    You could also make it portable like this.
    Code:
       if ( file )
       {
          size_t i;
          static const char charset[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
          int letter[sizeof charset - 1] = {0};
          for ( ;; )
          {
             size_t j;
             int c = fgetc(file);
             if ( c == EOF )
             {
                break;
             }
             for ( j = 0; j < sizeof letter / sizeof *letter; ++j )
             {
                if ( toupper(c) == charset[j] )
                {
                   ++letter[j];
                   break;
                }
             }
          }
          fclose(file);
          for ( i = 0; i < sizeof letter / sizeof *letter; ++i )
          {
             printf("'%c' : %d\n", charset[i], letter[i]);
          }
       }
    Last edited by Dave_Sinkula; 04-22-2005 at 09:58 PM. Reason: Changed display output to 'charset[i]' in second example; and declaration of letter[] size. Oh, heck, one more: loop control for j.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  6. #6
    Registered User
    Join Date
    Apr 2005
    Posts
    67
    Huh...you all gave me some nice ideas. I must learn arrays now. Thanks guys, for your help and your time!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Crazy Assignment Operator Semantics
    By SevenThunders in forum C++ Programming
    Replies: 7
    Last Post: 01-22-2009, 01:08 PM
  2. assignment operator for static array inside a class
    By acosgaya in forum C++ Programming
    Replies: 3
    Last Post: 07-27-2008, 11:11 AM
  3. Assignment Operator, Memory and Scope
    By SevenThunders in forum C++ Programming
    Replies: 47
    Last Post: 03-31-2008, 06:22 AM
  4. Replies: 8
    Last Post: 03-10-2008, 11:57 AM
  5. C Assignment
    By pardon37 in forum C Programming
    Replies: 0
    Last Post: 07-20-2002, 06:13 AM