Turn Desktop View Off
by Dinesh Thakur

Let us use an array of characters (str) to store the string and variables nletter, ndigit, nspace and nother to count the letters, digits, white spaces and other characters, respectively.

 The program given below first reads a string from the keyboard using the gets function and then uses a while loop to determine the desired counts. An if-else-if statement is used within the while loop to test the ith character and update the respective counter. Note the use of variable ch to minimize access to the array element (possibly improving its efficiency) as well as to improve the readability of the code. Finally, the program prints the counts.

/* Count letters, digits, whitespaces and other chars in a given string */
#include <stdio.h>
void main()
      char str [81];
      int nletter, ndigit, nspace, nother; /* char counts */
      int i;
      printf("Enter a line of text:\n");
      /* count characters in string str */
      nletter = ndigit = nspace = nother = 0; /* init counts */
      i = 0;
      while (str[i] != '\0')
              char ch= str[i];
              if (ch>= 'A' && ch<= 'Z' || ch>= 'a' && ch<= 'z')
              else if (ch>= '0' && ch<= '9')
              else if (ch == ' ' || ch =='\n' || ch == '\t')
              else nother++;
              /* print counts */
              printf("Letters: %d \tWhite spaces : %d", nletter, nspace);
              printf(" Digits : %d \tOther chars : %d\n", ndigit, nother);
The output of the program is given below
               C Program to Count Digits,White Space,Others