Hello,
This is a program which creates two arrays and a variable :
1. one for each alphabet
Code:
int char_array[MAXCHAR] = {0};
(MAXCHAR = 26);
2. one for each digit
Code:
int digit_array[MAXDIGIT] = {0};
(MAXDIGIT = 9);
3. variable counter for all other characters
Code:
int other_char = 0;
The program reads a file test1.txt and increments the frequency of each digit or alphabet or character in the assigned array or variable. (AN ASSUMPTION IS MADE THAT ALL CHARACTERS READ ARE LOWER CASE)
The program works fine when its reading digits or special characters but does not work when its reading alphabets and doesn't enter the condition :
Code:
else if (c >= 'a' && c >= 'z')
++char_array[c - 'a'];
Can anyone help me on this
The code is listed as follows :
Code:
#include<stdio.h>
/* ******************************************************************************************* */
/* This program prints an array of the frequencies of characters in a file input */
/* ******************************************************************************************* */
/* Constant declarations to define size for arrays containing 26 alphabets and 10 digits */
# define MAXCHAR 26
# define MAXDIGIT 10
int main()
{
/* variables 'c' stores the character read from the file */
/* Arrays char_array[] and digit_array[] are declared and elements are initialized to zero */
/* Arrays char_array[] and digit_array[] store frequency of characters and digits in the file read */
/* variable other_char stores the frequency of all other characters and is initialized to zero */
int c;
int char_array[MAXCHAR] = {0};
int digit_array[MAXDIGIT] = {0};
int other_char = 0;
/* Declare a file pointer fp and open the file test1.txt to read the input */
FILE *fp;
fp = fopen("test1.txt", "r+");
/* start the while loop after that and read the input into 'c' untill the end of file */
while((c = getc(fp)) != EOF)
{
/* If character read is a digit then increase the assigned character frequency by 1 */
if (c >= '0' && c <= '9')
++digit_array[c - '0'];
/* If character read is an alphabet then increase the assigned character frequency by 1 */
else if (c >= 'a' && c >= 'z')
++char_array[c - 'a'];
/* character read is special character hence increment special character count */
else
++other_char;
}
/* use a variable counter to print the elements of the arrays declared in the beginning */
int counter;
for(counter = 0; counter < MAXDIGIT; ++counter)
{
if (digit_array[counter] == 0)
continue;
else
printf("%d\n", digit_array[counter]);
}
for(counter = 0; counter < MAXCHAR; ++counter)
{
printf("%d", char_array[counter]);
}
printf ("%d\n", other_char);
fclose(fp);
return 0;
}