Stop learning alone!

Learn faster and stay on-track by joining this free class with other self-learners.

Register for Programming in C now.

Programming in C

Class length: 8 weeks. Start anytime.

Creator: kday

Status: Established

Join this class!

Lesson 1: Assignment 5: Arrays

Complete Exercise 1-13 and Exercise 1-14 on page 24.

Homework Submissions

3 total

wborskey (Self-grade: Outstanding)
Submitted 3 months ago | Permalink | Time spent: 1 minute
#include <stdio.h>
#define IN 1
#define OUT 0
main()
{
	int lc, state, input;
	int data[20] = {0};
	state = OUT;
	lc = 0;
	while ((input = getchar()) != EOF)
	{
		if (input < 0x41 || input < 0x61 && input > 0x5A)
			{
				state = OUT;
				++data[lc];
				lc = 0;	
			}
		else if (lc >= 20)
			{
				printf("This program does not support words longer than 20 characters and has been terminated.\n");
				printf("Results are not accurate.\nPlease check your file for words that are too long.\n");
				break;	
			}
		else
			{
				state = IN;
				++lc;
			}
	}
	printf("Word length histogram:\n----------------------\n");
	histogram(data);	
}

histogram(int *data)
{
	int i, j;
	for (i = 1; i < 20; i++)
	{
		if (data[i] == 0) 
			{ 
				continue; 
			}
		printf("|%.2d|", i);
		for (j = 0; j < data[i]; ++j)
			{
				putchar('#');
			}
		putchar('\n');
	}		
}
Crisciple (Self-grade: Could be better)
Submitted 10 months ago | Permalink | Time spent: 1 hour

Exercise 1-13

Write a program to print a histogram of the lengths of words in its input. It is easy to draw the histogram with the bars horizontal; a vertical orientation is more challenging.

Input:

qwe

qw

q

EOF

Output:

Word length count

0: 1 1: 1 2: 1 3: 1 4: 0 5: 0 6: 0 7: 0 8: 0 9: 0

Exercise 1-14

Write a program to print a histogram of the frequencies of different characters in its input.

Admittedly I didn't make the time to figure it out, so I looked at arideden's work and used his code to make sense of the exercise. When I realised that chars[256] was a counter for every character in the ASCII set, things were clearer.

Input:

hello himeso

Output:

tab: # n: # Space: # e: ## h: ## i: # l: ## m: # o: ## s: #

// Exercise 1-13
#include <stdio.h>
#define YES	1
#define NO 	0

/* Write a program to print a histogram of the lengths of words in its input.
 * It is easy to draw the histogram with the bars horizontal; a vertical orientation is more challenging
 *
 * For each consecutive letter or digit, add one to a count for word lengths of 0-9 (for tests purposes)
 * Print each word length count on a new line starting from 0 up to 9
 */

int main(void) {
	int c, prevWS, wlength;
	int wcount[10];

	prevWS = NO;
	wlength = 0;

	int i = 0;
	for (; i <10; ++i) {					// assign each element to 0
		wcount[i] = 0;
	}

	while ((c = getchar()) != EOF) {
		if (c == ' ' || c == '\n' || c == '\t') {	// if input is whitespace then
			prevWS = YES;				// set flag for being a whitespace character
			++wcount[wlength];			// increment wcount of the current word length
			wlength = 0;				// reset wlength to count new word length
		}
		else {						// if a character then
			++wlength;				// increment word length
			prevWS = NO;				// set flag for being a character or digit
		}
	}
	printf("Word length count\n======\n");	// print header
	for(i = 0; i < 10; i++) {				// print word lengths on a new line
		printf("%d: %3d\n", i, wcount[i]);
	}
}

// Exercise 1-14
#include <stdio.h>

/* Write a program to print a histogram of the frequencies of different characters in its input.
 *
 * User inputs a string of characters; The program takes that string and prints a list
 * of the frequency of each character.
 */
int main(void) {
	int c, i, j;
	int chars[256];		// a counter for every character in the ASCII set

	for (i = 0; i < 256; ++i) {
		chars[i] = 0;
	}

	// check each input and increment the relative element
	while ((c = getchar()) != EOF) {
		++chars[c];
	}

	// print only those characters that were received
	for (i = 0; i < 256; ++i) {			// go through every element in chars
		if (chars[i] > 0) {
			// print headers
			if (i == ' ')
				printf(" Space: ");
			else if (i == '\n')
				printf("    \\n: ");
			else if (i == '\t')
				printf("   tab: ");
			else
				printf("%6c: ", i);

			for (j = 0; j < chars[i]; ++j)	// print a # for every tally of each element; chars[i] is the tally
				putchar('#');		// and we need to go through each from 0 to the final tally of that
								// element
			printf("\n");
		}
	}
}
arideden (Self-grade: Outstanding)
Submitted 1 year ago | Permalink | Time spent: 2 hours
1.13:
#include <stdio.h>

#define IN  1 /* inside a word */
#define OUT 0 /* outside a word */

/* draw a vertical histogram of length of words */

main() {

  int c, i, j, state, nc, maxlength;
  int nwords[10];

  state = OUT;
  nc = maxlength = 0;

  /* nwords is an array whose first element, 0, corresponds to
  1 letter words, up to 9 which corresponds to 10 or more letter
  words */
  for (i = 0; i < 10; ++i)
    nwords[i] = 0;

  while ((c = getchar()) != EOF) {
    if (c == ' ' || c == '\n' || c == '\t') {
      if (state == IN) {
        state = OUT;
        if (nc >= 10) /* catchall for words of 10 letters or more */
          ++nwords[9];
        else
          ++nwords[nc - 1];
        nc = 0;
      }
    } else {
      state = IN;
      ++nc;
    }
  }
  /* determine longest word */
  for (i = 0; i < 10; ++i)
    if (nwords[i] > maxlength)
      maxlength = nwords[i];

  for (i = maxlength; i > 0; --i) {
    for (j = 0; j < 10; ++j) {
      if (nwords[j] >= i)
        printf(" # ");
      else
        printf("   ");
    }
    printf("\n");
  }
  for (i = 0; i < 10; ++i) {
    if (i == 9)
      printf("10+");
    else
      printf(" %d ", i + 1);
  }
  putchar('\n');
}


Sample interaction:
> echo "rattlesnakes exploitation computerized crossing cyanide one two six" | ./a.out
       #                    # 
       #                    # 
       #           #  #     # 
 1  2  3  4  5  6  7  8  9 10+


1.14:
#include <stdio.h>

/* print histogram of frequencies of
   different characters in input */

main() {
  /* The standard ascii character set fits in a single byte
     so if we allocate input in each of 256 slots we are
     sure to include everything. As this would be too
     unwieldy to print out as a histogram we will only
     print those characters which actually occur. */
  int characters[256];
  int c, i, j;

  c = 0;
  for (i = 0; i < 256; ++i)
    characters[i] = 0;

  while ((c = getchar()) != EOF)
    ++characters[c];

  for (i = 0; i < 256; ++i) {
    if (characters[i] > 0) {
      /* need to print representations of blank characters
         so we can see them and so they don't break
         the layout */
      if (i == ' ')
        printf("space  ");
      else if (i == '\n')
        printf("   \\n  ");
      else if (i == '\t')
        printf("  tab  ");
      else
        printf("%5c  ", i);
      for (j = 0; j < characters[i]; ++j)
        putchar('#');
      printf("\n");
    }
  }
}

Sample interaction:
> echo "hello curiousreef.com" | ./a.out
   \n  #
space  #
    .  #
    c  ##
    e  ###
    f  #
    h  #
    i  #
    l  ##
    m  #
    o  ###
    r  ##
    s  #
    u  ##

Comments:

ab_as_bc
1 year ago

Hey, I had been working on these two problems for a few days and have gotten nowhere so I hope that you don't mind that I used yours as a base to work off of.

arideden
1 year ago

Not at all

Sign up or log in to comment