Nov 15, 2011

K&R C Program Exercise 1-13

K and R C Programs Exercises provides the solution to all the exercises in the C Programming Language, second addition, by Brian W.Keringhan and Dennis M.Ritchie(Prentice Hall,1988). You can learn and solve K&R C Programs Exercise. K and R solution to print a histogram of the lengths of words in its input. Read more about C Programming Language .

/***********************************************************
* You can use all the programs on  www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
* 
*                      Happy Coding
***********************************************************/



#include <stdio.h>

#define MAXLN 10

int main(void)
{
 int c;
 int inspace = 0;
 long lengtharr[MAXLN + 1];
 int wordlen = 0;

 int firstletter = 1;
 long value = 0;
 long maxval = 0;
 int index = 0;
 int done = 0;

 for(index = 0; index <= MAXLN; index++)
 {
  lengtharr[index] = 0;
 }

 while(done == 0)
 {
  c = getchar();

  if(c == ' ' || c == '\t' || c == '\n' || c == EOF)
  {
   if(inspace == 0)
   {
    firstletter = 0;
    inspace = 1;

    if(wordlen <= MAXLN)
    {
     if(wordlen > 0)
     {
      value = ++lengtharr[wordlen - 1];
      if(value > maxval)
      {
       maxval = value;
      }
     }
    }
    else
    {
     value = ++lengtharr[MAXLN];
     if(value > maxval)
     {
      maxval = value;
     }
    }
   }
   if(c == EOF)
   {
    done = 1;
   }
  }
  else
  {
   if(inspace == 1 || firstletter == 1)
   {
    wordlen = 0;
    firstletter = 0;
    inspace = 0;
   }
   ++wordlen;
  }
 }

 for(value = maxval; value > 0; value--)
 {
  printf("%4d  | ", value);
  for(index = 0; index <= MAXLN; index++)
  {
   if(lengtharr[index] >= value)
   {
    printf("*  ");
   }
   else
   {
    printf("   ");
   }
  }
  printf("\n");
 }
 printf("      +");
 for(index = 0; index <= MAXLN; index++)
 {
  printf("---");
 }
 printf("\n       ");
 for(index = 0; index < MAXLN; index++)
 {
  printf("%2d ", index + 1);
 }
 printf(">%d\n", MAXLN);

 return 0;
}
Read more Similar C Programs
C Basic

K and R C Programs Exercise

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it


(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

List of C Programs