Search code examples
calgorithmuppercaselowercase

Finding frequency of characters both upper case and lower case in a file c program


I tried a lot of thing but when I chose 2 to count upper case and lower case separately the result was garbage, I don't know what is wrong with this, while doesn't care if lower case or upper case it still works correctly.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
  int i,h,k ,count[26] = {0}, nam[26] = {0};
  char c[1000];
  FILE *fptr;
  fptr=fopen("tep1.txt","w");
  if(fptr==NULL){
    printf("Error!");
    exit(1);
  }
  printf("a String please:\n");
  gets(c);
  fprintf(fptr,"%s",c);
  fclose(fptr);
  printf("discern between upper case and lower case? 0=no, 1=yes");
  scanf("%d",&h);

  if(h==0){    
    while (c[i] != '\0'){     
      if (c[i] >= 'a' && c[i] <= 'z') 
        count[c[i]-'a']++;

      if (c[i]>='A' &&c[i]<='Z')
        count[c[i]-'A']++;
      i++;
    }

    for (i = 0; i < 26; i++){
      if (count[i] != 0)
        printf("%c %c appears %d times on file.\n",i+'a',i+'A',count[i]);
    }
    return 0;
  }
  if(h==1){    
    while (c[i]|c[k] != '\0') {      
      if (c[i] >= 'a' && c[i] <= 'z') 
        count[c[i]-'a']++;
      i++;
      if (c[k]>='A' &&c[k]<='Z')
        nam[c[k]-'A']++;
      k++;
    }

    for (i = 0; i < 26; i++){
      if (count[i] != 0)
        printf("%c %c appears %d times on file.\n",i+'a',count[i]);      
    }

    for (k = 0; k < 26; k++){
      if (nam[k] != 0)
        printf("%c %c appears %d times on file.\n",k+'A',nam[k]);      
    }

    return 0;
  }
}

Solution

    • First, you have to initialize your integers like i = 0.
    • Second thing is for count upper and lower case, problem is in printing.In print function you have written %c two times and one %d, but gives only two arguments.
    • Just replace your printf function from,

      printf("%c %c appears %d times on file.\n",i+'a',count[i]);

      to

      printf("%c appears %d times on file.\n",i+'a',count[i]); and your problem will be solved.