C Arrays

Here are some C programs from the K&R book with reference to arrays. This resonated with the Perl hashes as this task is nearly always done with a hash, but as C has no hashes, here we go with an array!

The first program classifies the input into whitespace, numbers and everything else. The important points here are:

  1. ctrl-D to make EOF happen from the keyboard on a  Mac
  2. While and for contracts don’t need {} when there is only one line following.
  3. EOF is a macro defined in stdio.h
  4. getchar() collects a single character from STDIN

Here is the code and the output:

# cat counter.c

#include <stdio.h>

int main( int argc, char *argv[]){

	int whitespace, other, counter, c;

	int digit[10];

	for(counter=0;counter<=9;counter++)
		digit[counter]=0;

	while( (c = getchar()) != EOF)
		if (c >= '0' && c <= '9')
			digit[c - '0']++;
		else if (c == ' ' || c == '\t' || c== '\n')
			whitespace++;
		else
			other++;

	printf("Digits = ");
	for(counter=0;counter<=9;counter++)
		printf("%d ", digit[counter]);

	printf(" whitespace = %d, other = %d\n", whitespace, other);

}

# ./counter < counter.c
Digits = 6 1 0 0 0 0 0 0 0 3  whitespace = 103, other = 379

That was pretty much straight from the book, notice i just directed the source file back into the compiled file as a source of input. I could have used any file for input, or even typed in from the keyboard.
The next one is an exercise to create a histogram of word lengths from a file or the keyboard, my histogram was the easier horizontal histogram! My solution is below with the source, compilation and running the code using the source file as input:

# cat histogram.c

#include <stdio.h>

main (){

	int counter, lettercount, c;
	int words[21];

	for (counter=0;counter<=20;counter++)
		words[counter]=0;

	lettercount = 0;

	while ((c = getchar()) != EOF ){

		if(c != ' ' && c != '\t' && c != '\n'){
			lettercount++;
		}else{
			words[lettercount]++;
			lettercount=0;
		}
	}

	printf("\n\nWord Length Histogram\n---------------------\n");
	for(counter=1;counter<=20;counter++){
		printf("%2d: ", counter);
		for (c=1;c <= words[counter];c++){
			printf("*");
		}
		printf("\n");
	}

}

./histogram < histogram.c 

Word Length Histogram
---------------------
 1: **********
 2: ***********
 3: *******
 4: ***
 5: *
 6: ****
 7:
 8: **
 9: **
10: **
11: *
12: ***
13: *
14: **
15:
16: *
17: *
18:
19:
20: *
This entry was posted in C and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *