Pages

This blog is under construction

Monday, January 21, 2019

Write a program that creates a char type array of 100 lowercase letters randomly and counts the occurrence of each letter in the array.

C Code :

 #include<stdio.h>
 #include<stdlib.h>
 void fintoccurrence(char arr[],int occ[]);

 void main()
    {
        
            int max=122,min=97,i, occ[26]={0};
            char arr[100];

             for (i = 0; i <100; i++)
              { 
                   int num = (rand() % (max - min + 1)) + min; 
                   arr[i]=(char)num;
              }    
           
             printf("\nHundred random characters\n");
              for( i=0;i<100;i++)
                { if(i==20 || i==40 || i==60 || i==80)
                    {printf("\n");
                    }
                   printf(" %c",arr[i]);
                }
    
         printf("\nOccurrence of each letter:\n");
         fintoccurrence(arr,occ);
    }
    

    void fintoccurrence(char arr[],int occ[])
     {    int i,oc,as=97;
           for( i=0;i<100;i++)
              {
                oc=(int)arr[i]-97;
                occ[oc]++;                     //Using Hashing concept
              }
       
          for( i=0;i<26;i++)
            {    if(i==10 || i==20)
                  { printf("\n");
                  }
                 printf("%c-%d\t",(char)as,occ[i]);
                     as++;
            }
              
      }

Output:

Hundred random characters                                                                                                                              
 n w l r b b m q b h c d a r z o w k k y                                                                                                               
 h i d d q s c d x r j m o w f r x s j y                                                                                                               
 b l d b e f s a r c b y n e c d y g g x                                                                                                               
 x p k l o r e l l n m p a p q f w k h o                                                                                                               
 p k m c o q h n w n k u e w h s q m g b                                                                                                               
Occurrence of each letter:                                                                                                                             
a-3     b-7     c-5     d-6     e-4     f-3     g-3     h-5     i-1     j-2                                                                           
k-6     l-5     m-5     n-5     o-5     p-4     q-5     r-6     s-4     t-0  

No comments:

Post a Comment