Count Upper, Lower case alphabets and digits in a file

Shankye 0 Tallied Votes 550 Views Share

It counts upper lower and digits in a file ..

#include <stdio.h>
#include <ctype.h>

#define file "count.c"

int main()
{
        
     FILE *fs;
// Data required 
     int Ualpha[26]={0};
     int Lalpha[26]={0};
     int nums[10]={0};
     int i;

     fs = fopen(file,"r");
     if(fs == NULL)
     {
          printf("Error");
          exit(0);
     }

     char ch;

     // Scan char by char and check for type
     while( (ch=getc(fs)) != EOF )
     {
         if(isupper(ch))
                Ualpha[ch-'A'] += 1;   // count UpperCases
         else if(islower(ch))
                Lalpha[ch-'a'] += 1;   // Count LowerCases
         else if(isdigit(ch))
                nums[ch-'0'] += 1;     // Count numerics
     }


     // print Uppercase counts
     for(i=0 ; i<26 ;i++)
            printf("%c ",'A'+i);
     printf("\n");
     for(i=0 ; i<26 ;i++)
       printf("%d ",Ualpha[i]);

     printf("\n\n\n");

     // print Lowercase counts
     for(i=0 ; i<26 ;i++)
            printf("%c ",'a'+i);
     printf("\n");
     for(i=0 ; i<26 ;i++)
       printf("%d ",Lalpha[i]);

     printf("\n\n\n");

     // print digits counts
     for(i=0; i<10 ; i++)
        printf("%d ",i);
      printf("\n");
     for(i=0; i<10 ; i++)
        printf("%d ",nums[i]);


     return(0);
}
Narue 5,707 Bad Cop Team Colleague

ch should be int if you want to test for EOF, and you have portability issues with such constructs as ch-'A'. I've seen worse, but you have some learning to do before I'd recommend posting examples for others to learn from.

Shankye 36 Junior Poster

ok ..
May i know what type of portability issue with ch-'A' ?

I am not new to C but im doing electronic and Communication engineering so know less about C programming .. Its just hobbie..

Narue 5,707 Bad Cop Team Colleague

>May i know what type of portability issue with ch-'A' ?
There's an implicit presumption that the letters or are consecutive. It's a very common failure amongst people who have only ever worked with ASCII or the lower seven bits of Unicode. The usual counter example is EBCDIC, where the latin alphabet characters are not adjacent.

For example, 'i' has a value of 137 in EBCDIC, but 'j' has a value of 145. Using the ch-'a' pattern, you would end up with incorrect values and probably an out of range access in the case where the result is used as an array index and the array size doesn't account for such a direct character set to index conversion when there's "dead space" in the character set.

Shankye 36 Junior Poster

Oh i dint knew that ..

vinitmittal2008 37 Junior Poster

I also dint know that..... Thanks Narue.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.